soul网关源码学习02-http应用示例运行
目标:
- 运行http-example。
- 走一遍divide、waf插件,实现转发、负载均衡、防火墙等功能。
一、启动项目
先启动后台管理系统(soul-admin)和网关(soul-bootstrap),然后启动soul-example模块的soul-example-http。
二、运行demo
打开系统,可以看到http模块的接口都被注册到网关中。
- 转发
直接访问http服务,不经过网关:
经过网关转发到http服务:
效果完全一样,实现了网关基本的转发功能。
- 负载均衡
修改http服务端口,新起一个端口为8189的服务,在选择器增加一个配置,端口为8189,权重都为50,模拟负载均衡。
从日志可以看出,请求平均转发到两个http服务,实现了负载均衡的功能。
- 防火墙
先开启waf插件
新增一个waf选择器,条件为header存在token=1
新增一个规则,当header存在token=1时,拒绝访问,返回403状态码
当header中没有参数时,返回正常
当header中有token=1时,返回403状态码
三、查看代码
查看配置文件application.yml,配置了soul,项目启动时会根据配置注册相应的接口到网关。
soul: # Soul 针对 SpringMVC 的配置项,对应 SoulHttpConfig 配置类
http:
adminUrl: http://localhost:9095 # Soul Admin 地址
port: 8188 #你本项目的启动端口
contextPath: /http # 设置在 Soul 网关的路由前缀,例如说 /order、/product 等等
appName: http # 应用名,未配置情况下,默认使用 `spring.application.name` 配置项
full: false # 设置true 代表代理你的整个服务,false表示代理你其中某几个controller
注意这里的full字段,项目启动时会先根据full字段判断注册所有接口还是部分接口,大概看了一下(后面在仔细研究),一个spring后置处理器,一个Listener监听器。
public Object postProcessAfterInitialization(@NonNull final Object bean, @NonNull final String beanName) {
if (soulSpringMvcConfig.isFull()) {
return bean;
}
// 如果为full为false,扫描注解去注册接口
}
private final AtomicBoolean registered = new AtomicBoolean(false);
public void onApplicationEvent(final ContextRefreshedEvent contextRefreshedEvent) {
if (!registered.compareAndSet(false, true)) { // 首次执行时为false,后续直接return
return;
}
if (soulSpringMvcConfig.isFull()) { // 如果为true,注册所有接口
RegisterUtils.doRegister(buildJsonParams(), url, RpcTypeEnum.HTTP);
}
}
通过http请求把接口注册到网关
public static void doRegister(final String json, final String url, final RpcTypeEnum rpcTypeEnum) {
try {
String result = OkHttpTools.getInstance().post(url, json);
if (AdminConstants.SUCCESS.equals(result)) {
log.info("{} client register success: {} ", rpcTypeEnum.getName(), json);
} else {
log.error("{} client register error: {} ", rpcTypeEnum.getName(), json);
}
} catch (IOException e) {
log.error("cannot register soul admin param, url: {}, request body: {}", url, json, e);
}
}
四、总结
-
divide插件、waf插件的配置增删改操作了一遍,即改即用,数据实时同步,很方便,很灵活。
-
通过配置文件大致阅读了一下代码,代码很优秀,带着疑问查资料学习了一下,尤其是spring的。
-
整个网关的设计思想、设计模式很值得学习,要通过学习转化为自己的知识运用到实际项目中去。