docker开箱即用的java版本nginx-clojure插件实现负载均衡
官方文档
- nginx-clojure.github.io
- 截止示例实现,nginx-clojure支持 Java 9、10、11、12
- 测试jdk17发现确实用不了,等以后支持再构建17相关版本
示例说明
- nginx做反向代理在我们开发运维的同志日常生活中已经非常常见,后端有多台服务的时候还可以用nginx做负债均衡
- 之前负载均衡都是使用upstream模块实现
- 但作为一个小javaer的我偶然看到眼前一亮的clojure
- 什么??java也可以写nginx插件,ok,那我们就使用java来写一个nginx的负载均衡小demo
java代码实现
加入maven依赖
<dependency>
<groupId>nginx-clojure</groupId>
<artifactId>nginx-clojure</artifactId>
</dependency>
java伪代码从多个地址按照权重返回
private static final WeightRandom<String> weightApp = RandomUtil.weightRandom(
CollUtil.newArrayList(
new WeightRandom.WeightObj<>("http://127.0.0.1:8080/app1", 0.5),
new WeightRandom.WeightObj<>("http://127.0.0.1:8080/app2", 0.5)
)
);
@Override
public Object[] invoke(Map<String, Object> req) throws IOException {
String myhost = weightApp.next();
NginxClojureRT.log.info("随机访问:" + myhost);
// 用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;
}
容器实例创建
拉取jdk8版本的nginx-clojure
nginx:
image: lianlianyi/nginx_clojure:0.5.3_jdk8
networks:
- npc_net
volumes:
- ./etc/nginx_clojure/nginx.conf:/nginx/conf/nginx.conf
# 程序生成的demo.jar
- ./data/nginx_clojure/my_nginx_clojure-1.0-SNAPSHOT.jar:/nginx/jars/demo.jar
# demo.jar需要依赖的库(不是必须)
- ./data/nginx_clojure/hutool-all-5.8.0.M3.jar:/nginx/jars/hutool-all-5.8.0.M3.jar
ports:
- 80:8080
- 443:443