这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
package com.bolingcavalry.handlerdemo;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.java.NginxJavaRingHandler;
import java.io.IOException;
import java.util.Map;
public class MyInitHandler implements NginxJavaRingHandler {
@Override
public Object[] invoke(Map<String, Object> map) throws IOException {
// 可以根据实际需求执行初始化操作,这里作为演示,只打印日志
NginxClojureRT.log.info("MyInitHandler.invoke executed");
return null;
}
}
jvm_handler_type 'java';
jvm_init_handler_name 'com.bolingcavalry.handlerdemo.MyInitHandler';
2022-02-05 23:02:37[info][73954][main]MyInitHandler.invoke executed
location /contentdemo {
# 第一个自定义属性
content_handler_property foo.name 'foo.value';
# 第二个自定义属性
content_handler_property bar.name 'bar.value';
# 逻辑处理类
content_handler_name 'com.bolingcavalry.handlerdemo.MyContentHandler';
}
package com.bolingcavalry.handlerdemo;
import nginx.clojure.Configurable;
import nginx.clojure.java.ArrayMap;
import nginx.clojure.java.NginxJavaRingHandler;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import static nginx.clojure.MiniConstants.CONTENT_TYPE;
import static nginx.clojure.MiniConstants.NGX_HTTP_OK;
public class MyContentHandler implements NginxJavaRingHandler, Configurable {
private Map<String, String> config;
/**
* location中配置的content_handler_property属性会通过此方法传给当前类
* @param map
*/
@Override
public void config(Map<String, String> map) {
this.config = map;
}
@Override
public Object[] invoke(Map<String, Object> map) throws IOException {
String body = "From MyContentHandler, "
+ LocalDateTime.now()
+ ", foo : "
+ config.get("foo.name")
+ ", bar : "
+ config.get("bar.name");
return new Object[] {
NGX_HTTP_OK, //http status 200
ArrayMap.create(CONTENT_TYPE, "text/plain"), //headers map
body
};
}
}
- 下面就是一个完整的rewrite handler,这些内容都是写在http配置内的:
# 1. 定义变量,用于保存路径
set $myhost "";
location /myproxy {
rewrite_handler_type 'java';
# 2. java代码中为变量赋值
rewrite_handler_name 'com.bolingcavalry.handlerdemo.MyRewriteProxyPassHandler';
# 3. 用变量的值作为地址进行跳转
proxy_pass $myhost;
}
package com.bolingcavalry.handlerdemo;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.java.NginxJavaRequest;
import nginx.clojure.java.NginxJavaRingHandler;
import java.util.Map;
import static nginx.clojure.java.Constants.PHASE_DONE;
public class MyRewriteProxyPassHandler implements NginxJavaRingHandler {
@Override
public Object[] invoke(Map<String, Object> req) {
// 根据业务情况定制计算出的path
String myhost = computeMyHost(req);
// 用setVariable方法设置myhost变量的值,这个myhost在这个location中被定义,跳转的时候就用这个值作为path
((NginxJavaRequest)req).setVariable("myhost", myhost);
// 返回PHASE_DONE之后,nginx-clojure框架就会执行proxy_pass逻辑,
// 如果返回的不是PHONE_DONE,nginx-clojure框架就把这个handler当做content handler处理
return PHASE_DONE;
}
/**
* 这里写入业务逻辑,根据实际情况确定返回的path
* @param req
* @return
*/
private String computeMyHost(Map<String, Object> req) {
// 确认是http还是https
String scheme = (String)req.get("scheme");
// 确认端口号
String serverPort = (String)req.get("server-port");
// /contentdemo是nginx.conf中配置的一个location,您可以根据自己的业务情况来决定返回值
String myhost = scheme + "://127.0.0.1:" + serverPort + "/contentdemo";
NginxClojureRT.log.info("pass address [" + myhost + "]");
return myhost;
}
}
- 如果您的环境中有注册中心,例如eureka或者nacos,您还可以取得后台服务列表,这样,不光是负载均衡,各种转发调度逻辑都可以在nginx上开发出来了
# 1. 定义变量,用于保存路径
set $myhost "";
location /myproxy {
# 指定access handler的类型是java
access_handler_type 'java';
# 指定access handler的执行类类
access_handler_name 'com.bolingcavalry.handlerdemo.BasicAuthHandler';
rewrite_handler_type 'java';
# 2. java代码中为变量赋值
rewrite_handler_name 'com.bolingcavalry.handlerdemo.MyRewriteProxyPassHandler';
# 3. 用变量的值作为地址进行跳转
proxy_pass $myhost;
}
package com.bolingcavalry.handlerdemo;
import nginx.clojure.java.ArrayMap;
import nginx.clojure.java.NginxJavaRingHandler;
import javax.xml.bind.DatatypeConverter;
import java.util.Map;
import static nginx.clojure.MiniConstants.DEFAULT_ENCODING;
import static nginx.clojure.MiniConstants.HEADERS;
import static nginx.clojure.java.Constants.PHASE_DONE;
public class BasicAuthHandler implements NginxJavaRingHandler {
@Override
public Object[] invoke(Map<String, Object> request) {
// 从header中获取authorization字段
String auth = (String) ((Map)request.get(HEADERS)).get("authorization");
// 如果header中没有authorization,就返回401错误,并带上body
if (auth == null) {
return new Object[] { 401, ArrayMap.create("www-authenticate", "Basic realm=\"Secure Area\""),
"<HTML><BODY><H1>401 Unauthorized.</H1></BODY></HTML>" };
}
// authorization应该是 : Basic xfeep:hello!,所以这里先将"Basic "去掉,然后再用":"分割
String[] up = auth.substring("Basic ".length()).split(":");
// 只是为了演示,所以账号和密码的检查逻辑在代码中是写死的,
// 如果账号等于"xfeep",并且密码等于"hello!",就返回PHASE_DONE,这样nginx-clojure就会继续执行后面的content handler
if (up[0].equals("xfeep") && up[1].equals("hello!")) {
return PHASE_DONE;
}
// 如果账号密码校验不过,就返回401,body内容是提示账号密码不过
return new Object[] { 401, ArrayMap.create("www-authenticate", "Basic realm=\"Secure Area\""),
"<HTML><BODY><H1>401 Unauthorized BAD USER & PASSWORD.</H1></BODY></HTML>" };
}
}
location /contentdemo {
# 第一个自定义属性
content_handler_property foo.name 'foo.value';
# 第二个自定义属性
content_handler_property bar.name 'bar.value';
content_handler_name 'com.bolingcavalry.handlerdemo.MyContentHandler';
# log handler类型是java
log_handler_type java;
# log handler的执行类
log_handler_name 'com.bolingcavalry.handlerdemo.MyLogHandler';
# 自定义属性,在MyLogHandler中作为是否打印User Agent的开关
log_handler_property log.user.agent on;
# 自定义属性,在MyLogHandler中作为日志目录
log_handler_property log.file.path logs/contentdemo.log;
}
package com.bolingcavalry.handlerdemo;
import nginx.clojure.Configurable;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.java.NginxJavaRequest;
import nginx.clojure.java.NginxJavaRingHandler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
public class MyLogHandler implements NginxJavaRingHandler, Configurable {
/**
* 是否将User Agent打印在日志中
*/
private boolean logUserAgent;
/**
* 日志文件路径
*/
private String filePath;
@Override
public Object[] invoke(Map<String, Object> request) throws IOException {
File file = new File(filePath);
NginxJavaRequest r = (NginxJavaRequest) request;
try (FileOutputStream out = new FileOutputStream(file, true)) {
String msg = String.format("%s - %s [%s] \"%s\" %s \"%s\" %s %s\n",
r.getVariable("remote_addr"),
r.getVariable("remote_user", "x"),
r.getVariable("time_local"),
r.getVariable("request"),
r.getVariable("status"),
r.getVariable("body_bytes_sent"),
r.getVariable("http_referer", "x"),
logUserAgent ? r.getVariable("http_user_agent") : "-");
out.write(msg.getBytes("utf8"));
}
return null;
}
@Override
public void config(Map<String, String> properties) {
logUserAgent = "on".equalsIgnoreCase(properties.get("log.user.agent"));
filePath = properties.get("log.file.path");
NginxClojureRT.log.info("MyLogHandler, logUserAgent [" + logUserAgent + "], filePath [" + filePath + "]");
}
// 下面这段代码来自官方demo,实测发现这段代码在打印日志的逻辑中并未发挥作用,
// 不论是否删除,日志输出的内容都是相同的
/*
@Override
public String[] variablesNeedPrefetch() {
return new String[] { "remote_addr", "remote_user", "time_local", "request", "status", "body_bytes_sent",
"http_referer", "http_user_agent" };
}
*/
}
2022-02-08 08:59:22[info][69035][main]MyLogHandler, logUserAgent [true], filePath [logs/contentdemo.log]
127.0.0.1 - x [08/Feb/2022:09:45:36 +0800] "GET /contentdemo HTTP/1.1" 200 "80" x PostmanRuntime/7.29.0