## 应用名称
spring.application.name=smartworkflowbusiness
## nacos配置中心请求地址
spring.cloud.nacos.config.server-addr=192.168.1.1:9001
## nacos 命名空间
spring.cloud.nacos.config.namespace=public
## nacos组
spring.cloud.nacos.config.group=DEFAULT_GROUP
## nacos配置中心环境
spring.profiles.active=test
## nacos注册中心地址
spring.cloud.nacos.discovery.server-addr=192.168.1.1:9001
## nacos 注册中心命名空间
spring.cloud.nacos.discovery.namespace=cf94d71d-81c8-4e6f-8c25-8bf14c870701
## nacos 运行注册发现
spring.cloud.nacos.discovery.enabled=true
spring.cloud.nacos.discovery.service=${spring.application.name}
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${alibaba-clound.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- nacso注册-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacso配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
package com.fast.cattsoft.nacos;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* @ClassName
* @Description
* @Author qiangsw
* @date 2020/9/12 10:31
* @Version 1.0
* TODO 获取某个服务注册信息
*/
@Component
public class NacosServiceIntance {
public static String nacosServerAddr;
public static String group;
public static String namespace;
@Value("${spring.cloud.nacos.discovery.server-addr}")
public void setNacosServerAddr(String nacosServerAddr) {
this.nacosServerAddr = nacosServerAddr;
}
;
@Value("${spring.cloud.nacos.config.group}")
private void setGroup(String group) {
this.group = group;
}
@Value("${spring.cloud.nacos.discovery.namespace}")
private void setNamespace(String namespace) {
this.namespace = namespace;
}
public static Instance getServiceIntance(String dataId) throws NacosException {
Properties properties = new Properties();
properties.put("serverAddr", nacosServerAddr);
properties.put("namespace", namespace);
NamingService namingService = NamingFactory.createNamingService(properties);
return namingService.selectOneHealthyInstance(dataId);
}
}
package com.cattsoft.gateway.service;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
/**
* @ClassName
* @Description
* @Author qiangsw
* @date 2020/8/25 14:56
* @Version 1.0
* TODO 动态获取nacos 配置信息更新网关路由信息
*/
@RestController
@Slf4j
public class RoutePublishService {
@Autowired
private DynamicRouteService dynamicRouteService;
@Value("${spring.cloud.nacos.config.server-addr}")
private String nacosServerAddr;
@Value("${spring.application.name}")
private String applicationName;
@Value("${spring.profiles.active}")
private String active;
@Value("${spring.cloud.nacos.config.group}")
private String group;
@Value("${spring.cloud.nacos.config.namespace}")
private String namespeac;
@PostConstruct
public void conversion() {
Properties properties = new Properties();
properties.put("serverAddr", nacosServerAddr);
properties.put("namespeac", namespeac);
String dataId = applicationName + "-" + active + ".properties";
log.info("nacos配置监听,namespeac[{}]#group[{}]#dataId[{}]", namespeac, group, dataId);
try {
ConfigService configService = NacosFactory.createConfigService(properties);
configService.addListener(dataId, group, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
log.info("nacos服务[{}]配置更新{}", applicationName, configInfo);
if (StringUtils.isEmpty(configInfo)) {
return;
}
List<String> list = Arrays.asList(configInfo.split("\\r\\n"));
List<String> ids = Optional.of(list).map(a -> list.stream().filter(filter -> {
String[] split1 = filter.split("=");
if (split1[0].indexOf("].id", 0) != -1) {
return true;
}
return false;
}).map(map -> {
String[] split = map.split("=");
return split[1];
}).collect(Collectors.toList())).get();
update(ids);
}
});
} catch (NacosException e) {
log.error("nacos热更新配置异常:", e);
}
}
public void update(List<String> ids) {
if (CollectionUtils.isEmpty(ids)) {
return;
}
ids.forEach(each -> {
RouteDefinition routeDefinition = new RouteDefinition();
routeDefinition.setId(each);
URI uri = null;
try {
uri = new URI("lb://" + each);
} catch (URISyntaxException e) {
log.info("路由id[{}]发生:", each, e);
return;
}
routeDefinition.setUri(uri);
FilterDefinition filterDefinition = new FilterDefinition();
filterDefinition.setName("StripPrefix");
Map<String, String> filterArgs = new LinkedHashMap();
filterArgs.put("_genkey_0", "1");
filterDefinition.setArgs(filterArgs);
List<FilterDefinition> filterDefinitions = Lists.newArrayList();
filterDefinitions.add(filterDefinition);
PredicateDefinition predicateDefinition = new PredicateDefinition();
predicateDefinition.setName("Path");
Map<String, String> PredicateDefinitionargs = new LinkedHashMap();
PredicateDefinitionargs.put("pattern", "/"+each+"/**");
predicateDefinition.setArgs(PredicateDefinitionargs);
List<PredicateDefinition> predicateDefinitions = Lists.newArrayList();
predicateDefinitions.add(predicateDefinition);
routeDefinition.setPredicates(predicateDefinitions);
routeDefinition.setFilters(filterDefinitions);
dynamicRouteService.updateRoute(routeDefinition);
});
}
@GetMapping("/doConversion")
public void doConversion() {
conversion();
}
}