pull/3/head
tanghc 4 years ago
parent 9e905666c8
commit a22bfb84db
  1. 38
      doc/docs/files/90011_原理分析之如何存储路由.md
  2. 2
      sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/AbstractConfiguration.java

@ -15,14 +15,9 @@ this.publisher.publishEvent(new HeartbeatEvent(this, this.nacosWatchIndex.getAnd
```java
public class AbstractConfiguration implements ApplicationContextAware, ApplicationListener<HeartbeatEvent> {
/**
* nacos事件监听,每次微服务变化会触发这个方法
* @see org.springframework.cloud.alibaba.nacos.discovery.NacosWatch NacosWatch
* @param heartbeatEvent
*/
@Override
public void onApplicationEvent(HeartbeatEvent heartbeatEvent) {
...这里加载路由信息
@EventListener(classes = HeartbeatEvent.class)
public void listenEvent(ApplicationEvent heartbeatEvent) {
// 有服务注册进来
}
}
```
@ -32,23 +27,26 @@ public class AbstractConfiguration implements ApplicationContextAware, Applicati
加载路由伪代码如下:
```java
public void onApplicationEvent(HeartbeatEvent heartbeatEvent) {
// 获取nacos中的服务实例列表
List<Instance> allInstances = namingService.getAllInstances(serviceName);
for(Instance instance : allInstances) {
// 微服务提供的接口
String url = "http://" + instance.getIp + ":" + instance.getPort + "/sop/routes";
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
@Override
public void onAddInstance(InstanceDefinition instance) {
String serviceName = instance.getServiceId();
String url = getRouteRequestUrl(instance);
log.info("拉取路由配置,serviceId: {}, url: {}", serviceName, url);
ResponseEntity<String> responseEntity = getRestTemplate().getForEntity(url, String.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
// 返回来的路由信息
String body = responseEntity.getBody();
...加载路由到本地
}
ServiceRouteInfo serviceRouteInfo = JSON.parseObject(body, ServiceRouteInfo.class);
baseRouteCache.load(serviceRouteInfo, callback -> routesProcessor.saveRoutes(serviceRouteInfo, instance));
} else {
log.error("拉取路由配置异常,url: {}, status: {}, body: {}", url, responseEntity.getStatusCodeValue(), responseEntity.getBody());
}
}
```
完整代码可参看`com.gitee.sop.gatewaycommon.manager.ServiceRoutesLoader.java`
参考代码:
- `com.gitee.sop.gatewaycommon.route.RegistryListener`以及实现类
- `com.gitee.sop.gatewaycommon.route.ServiceRouteListener`
路由的存储方式是一个Map,key为路由id,即接口名+版本号。
@ -56,7 +54,7 @@ public void onApplicationEvent(HeartbeatEvent heartbeatEvent) {
/**
* key:nameVersion
*/
private Map<String, ZuulTargetRoute> nameVersionTargetRouteMap;
private static final Map<String, GatewayTargetRoute> routes = synchronizedMap(new LinkedHashMap<>());
```
因为客户端调用接口都会传递一个接口名和版本号,因此通过这两个字段能够很快查询出路由信息,进行路由转发操作。

@ -81,7 +81,7 @@ public class AbstractConfiguration implements ApplicationContextAware, Applicati
* @param heartbeatEvent
*/
@EventListener(classes = HeartbeatEvent.class)
public void listenNacosEvent(ApplicationEvent heartbeatEvent) {
public void listenEvent(ApplicationEvent heartbeatEvent) {
// 没有启动完毕先等待
if (!isStartupCompleted) {
lock.lock();

Loading…
Cancel
Save