Commit 0737f607 authored by zhang 张号彬's avatar zhang 张号彬

修改NacosConfigListener

parent 6db69bca
package com.elitesland;
import com.elitesland.router.config.NacosConfigListener;
import com.elitesland.router.service.DynamicRouteService;
import com.elitesland.router.util.GateWayNacosUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
/**
* <p>
......
......@@ -21,5 +21,4 @@ public class GatewayRouteDefinition{
private String uri;
//路由执行的顺序
private int order = 0;
//此处省略get和set方法
}
\ No newline at end of file
......@@ -18,11 +18,8 @@ import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
/*
......@@ -39,10 +36,6 @@ public class NacosConfigListener implements CommandLineRunner {
private DynamicRouteService dynamicRouteService;
@Autowired
private InMemoryRouteDefinitionRepository inMemoryRouteDefinitionRepository;
//由于可能根据需要在定时任务中引用该list,因此使用线程安全的SynchronizedListlist
public static List<GatewayRouteDefinition> list = Collections.synchronizedList(new ArrayList<>());
@Override
public void run(String... args) {
getConfig();
......@@ -54,14 +47,13 @@ public class NacosConfigListener implements CommandLineRunner {
ConfigService configService = gateWayNacosUtils.getNacosConfigService();
Gson gson = new Gson();
//注册nacos配置监听,当nacos配置信息发生改变时刷新本地内存中Gateway Route规则信息
refreshLocalRoute(routeDefinitions, gson,true);
refreshLocalRoute(routeDefinitions, gson, true);
String group = gateWayNacosUtils.getNacosConfigGroup();
String routeConfigDataId = gateWayNacosUtils.getNacosConfigDataIdForGateWayDefinition();
configService.addListener(routeConfigDataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println(configInfo+"------->");
refreshLocalRoute(configInfo, gson,false);
refreshLocalRoute(configInfo, gson, false);
}
@Override
public Executor getExecutor() {
......@@ -73,24 +65,22 @@ public class NacosConfigListener implements CommandLineRunner {
e.printStackTrace();
}
}
/**
* 根据nacos配置信息,刷新本地Gateway RouteDefinition
*/
private void refreshLocalRoute(String initConfigInfo, Gson gson, boolean t) {
//删除内存中已存在的动态路由配置信息
if(list.size() > 0){
list.forEach(gatewayRouteDefinition -> {
dynamicRouteService.delete(gatewayRouteDefinition.getId());
Flux<RouteDefinition> routeDefinitions = inMemoryRouteDefinitionRepository.getRouteDefinitions();
//由于不存在空指针情况,因此无需空指针判断
routeDefinitions.subscribe(routeDefinition -> {
dynamicRouteService.delete(routeDefinition.getId());
});
list = Collections.synchronizedList(new ArrayList<>());
}
JsonArray jsonArray = gson.fromJson(initConfigInfo, JsonArray.class);
jsonArray.forEach(routeDefinitionAsJsonObject -> {
GatewayRouteDefinition gatewayRouteDefinition = gson.fromJson(routeDefinitionAsJsonObject, GatewayRouteDefinition.class);
RouteDefinition definition = convertRouteDefinition(gatewayRouteDefinition);
dynamicRouteService.add(definition);
list.add(gatewayRouteDefinition);
});
}
......@@ -101,7 +91,6 @@ public class NacosConfigListener implements CommandLineRunner {
RouteDefinition definition = new RouteDefinition();
definition.setId(gwdefinition.getId());
definition.setOrder(gwdefinition.getOrder());
//设置断言
ArrayList<PredicateDefinition> pdList = new ArrayList<>();
ArrayList<GatewayPredicateDefinition> gatewayPredicateDefinitionList = gwdefinition.getPredicates();
......@@ -112,7 +101,6 @@ public class NacosConfigListener implements CommandLineRunner {
pdList.add(predicate);
});
definition.setPredicates(pdList);
//设置过滤器
ArrayList<FilterDefinition> filters = new ArrayList();
ArrayList<GatewayFilterDefinition> gatewayFilters = gwdefinition.getFilters();
......@@ -123,7 +111,6 @@ public class NacosConfigListener implements CommandLineRunner {
filters.add(filter);
});
definition.setFilters(filters);
URI uri = null;
if (gwdefinition.getUri().startsWith("http")) {
uri = UriComponentsBuilder.fromHttpUrl(gwdefinition.getUri()).build().toUri();
......
package com.elitesland.router.controller;
import com.elitesland.router.bean.GatewayRouteDefinition;
import com.elitesland.router.service.DynamicRouteService;
import com.elitesland.router.service.GatewayRoutesInNacosConfigService;
......@@ -8,12 +7,16 @@ import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.*;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
/*
......@@ -21,8 +24,8 @@ import java.util.ArrayList;
*@Date 2021-02-10 19:17
*@Description
* http://localhost:9040/actuator/gateway/routes 通过acutator查询route配置信息
* 在生产环境中配置信息将通过redis进行查询及持久化操作
*/
@RestController
@RequestMapping("/route")
public class RouteController {
......@@ -31,31 +34,27 @@ public class RouteController {
@Autowired
PropertiesRouteDefinitionLocator PropertiesRouteDefinitionLocator;
@Autowired
private DynamicRouteService dynamicRouteService;
/**
*增加路由
*/
@PostMapping("/addOrUpdate")
public GatewayRouteDefinition addOrUpdate(@RequestBody GatewayRouteDefinition gwdefinition) {
return gatewayRoutesInNacosConfigService.addOrUpdateRouteDefinitiToNacosServer(gwdefinition);
public Mono<GatewayRouteDefinition> addOrUpdate(@RequestBody GatewayRouteDefinition gwdefinition) {
return Mono.just(gatewayRoutesInNacosConfigService.addOrUpdateRouteDefinitiToNacosServer(gwdefinition));
}
/**
*删除路由
*/
@DeleteMapping("/routes/{id}")
public String delete(@PathVariable String id) {
return gatewayRoutesInNacosConfigService.deleteRouteDefinitiToNacosServer(id);
public Mono<String> delete(@PathVariable String id) {
return Mono.just(gatewayRoutesInNacosConfigService.deleteRouteDefinitiToNacosServer(id));
}
/**
* 获取nacos里配置的动态路由配置信息
* */
*/
@GetMapping("/routes/all")
public Flux<ArrayList<GatewayRouteDefinition>> all() {
public Flux<GatewayRouteDefinition> routes() {
Gson g = new Gson();
ArrayList<GatewayRouteDefinition> list = new ArrayList<>();
JsonArray gatewayDefinitionsFromNacosServer = gatewayRoutesInNacosConfigService.getGatewayDefinitionsFromNacosServer();
......@@ -63,15 +62,14 @@ public class RouteController {
GatewayRouteDefinition gatewayRouteDefinition = g.fromJson(o, GatewayRouteDefinition.class);
list.add(gatewayRouteDefinition);
});
return Flux.just(list);
return Flux.fromIterable(list);
}
/**
* 获取本地所有的动态路由配置信息
* */
@GetMapping("/all")
public Flux<RouteDefinition> all1() {
Flux<RouteDefinition> routeDefinitions = PropertiesRouteDefinitionLocator.getRouteDefinitions();
routeDefinitions.subscribe();
return routeDefinitions;
* 获取本地所配置文件中所有的静态路由配置信息
*/
@GetMapping("staticRoutes/all")
public Flux<RouteDefinition> staticRoutes() {
return PropertiesRouteDefinitionLocator.getRouteDefinitions();
}
}
\ No newline at end of file
package com.elitesland.router.service;
import com.elitesland.router.util.GateWayNacosUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationEventPublisher;
......@@ -14,7 +16,6 @@ import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
/*
*@Author Horbin.Zhang
*@Date 2021-02-10 19:29
......@@ -30,8 +31,10 @@ public class DynamicRouteService implements ApplicationEventPublisherAware {
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher publisher;
@Autowired
GatewayProperties gatewayProperties;
private ApplicationEventPublisher publisher;
private ArrayList<String> routeIdInMemory = new ArrayList<>();
......@@ -46,7 +49,7 @@ public class DynamicRouteService implements ApplicationEventPublisherAware {
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "删除成功!";
return "添加成功!";
}
/**
......
......@@ -6,20 +6,10 @@ import com.elitesland.router.util.GateWayNacosUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.CachingRouteDefinitionLocator;
import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.stereotype.Service;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import java.util.List;
/*
*@Author Horbin.Zhang
......@@ -28,10 +18,13 @@ import java.util.List;
*/
@Service
public class GatewayRoutesInNacosConfigService {
@Autowired
private GateWayNacosUtils gateWayNacosUtils;
@Autowired
org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator propertiesRouteDefinitionLocator;
@Autowired
private DynamicRouteService dynamicRouteService;
......@@ -40,16 +33,6 @@ public class GatewayRoutesInNacosConfigService {
public GatewayRouteDefinition addOrUpdateRouteDefinitiToNacosServer(GatewayRouteDefinition gwdefinition) {
try {
//清除静态配置路由信息中存在的动态路由信息
// Flux<RouteDefinition> routeDefinitions = propertiesRouteDefinitionLocator.getRouteDefinitions();
// routeDefinitions.subscribe( routeDefinition ->{
// if (routeDefinition.getId().equalsIgnoreCase(gwdefinition.getId())) {
// System.out.println(routeDefinition.getId()+"++++++++++++++++++++++++++++++++++++++++++========");
// dynamicRouteService.delete(routeDefinition.getId());
// }
// });
Gson gson = new Gson();
String gateWayDefinitions = gateWayNacosUtils.getRouteDefinitionsFromNacosServer();
boolean flag = false;
......@@ -68,7 +51,6 @@ public class GatewayRoutesInNacosConfigService {
}
JsonElement jsonElement = gson.toJsonTree(gwdefinition, GatewayRouteDefinition.class);
newConfig.add(jsonElement);
ConfigService configService = gateWayNacosUtils.getNacosConfigService();
String group = gateWayNacosUtils.getNacosConfigGroup();
String routeConfigDataId = gateWayNacosUtils.getNacosConfigDataIdForGateWayDefinition();
......
package com.elitesland.router.util;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Value;
......@@ -31,17 +30,19 @@ public class GateWayNacosUtils {
String initConfigInfo = configService.getConfig(routeConfigDataId, group, 5000);
return initConfigInfo;
}
public ConfigService getNacosConfigService() throws Exception{
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
return configService;
}
public String getNacosConfigGroup(){
return this.group;
}
public String getNacosConfigDataIdForGateWayDefinition(){
return this.routeConfigDataId;
}
}
......@@ -75,24 +75,16 @@ spring:
# - Header=orgCode,zz00001
# filters:
# - RewritePath=/mdxt/(?<segment>.*),/$\{segment}
nacos:
discovery:
server-addr: frps.elitescloud.com:25145
# enabled: true
# register-enabled: true
gateway:
nacos:
routeinfo:
dataid: gateway.routeinfo.json
group: DEFAULT_GROUP
# 内部端点暴露
management:
endpoints:
......@@ -102,17 +94,12 @@ management:
endpoint:
health:
show-details: always
# datasource:
# url: jdbc:mysql://frps.elitescloud.com:25148/jyj_fc?rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
# username: root
# password: 123456
# tomcat:
# ignore-exception-on-pre-load:
jwt:
header: Authorization
# 令牌前缀
......
......@@ -3,9 +3,5 @@ spring:
#active: ${profileActive}
application:
name: yst-gateway
server:
port: 9040
\ No newline at end of file
# servlet:
# context-path: ""
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment