1、首先引入nacos的maven包
<!--引入配置中心阿里巴巴--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!--引入注册中心阿里巴巴--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
注意前提在dependencyManagement要引入,版本号自行规定,最好与SpringCloud一致
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring-cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency>
2、在配置文件application.properties或bootstrap.yml(需引入SpringCloud bootstrap)中添加nacos地址
spring: cloud: nacos: config: server-addr: xxx.xxx.xxx.xxx:8848 namespace: xxxxx file-extension: yaml group: AMT_GROUP refresh-enabled: true shared-configs[0]: data-id: db_config.yaml refresh-enabled: true group: AMT_GROUP discovery: server-addr: xxx.xxx.xxx.xxx:8848 application: name: amt-atw
3、代码实现
配置拉取:直接用@Value注解即可,注意@Value获取时需要将该类放入Spring容器中管理
@Configuration
public class RedisSubListenerConfig {
//配置中心中有配置com.netty.closeChannel
@Value("${com.netty.closeChannel:closeChannel}")
public String closeChannel;
//other code here
}
注册中心:配置文件中加入了注册中心配置即可。
调用注册中心的服务:
用SpringCloud的Feign组件
//在启动类中加入注解
@EnableDiscoveryClient //nacos的discovery
@EnableFeignClients //feign
public class FeignSpringCloud {
public static void main(String[] args) {
SpringApplication.run(FeignSpringCloud.class,args);
}
}
创建Feign调用接口:
//name对应的是注册中心的微服务提供方name,fallbackFactory 为熔断后返回 @GetMapping中的值是提供方对应的地址
@FeignClient(name = "xxxxx-service",fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {
@GetMapping("/dept/getById/{id}")
public Dept getById(@PathVariable("id")Integer id);
@GetMapping("/dept/getAll")
public List<Dept> getAll();
@PostMapping("/dept/add")
public boolean addDept(Dept dept);
}
熔断fallbackFacotory:
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory {
@Override
public DeptClientService create(Throwable throwable) {
return new DeptClientService() {
@Override
public Dept getById(Integer id) {
return new Dept().setId(id)
.setName("id => "+ id +"没有对应的信息,客户端提供了降级的信息,这个服务现在已经关闭")
.setDb_source("没有数据~");
}
@Override
public List<Dept> getAll() {
return null;
}
@Override
public boolean addDept(Dept dept) {
return false;
}
};
}
}
或者指定fallbackfactory为自定义的类,然后实现feign的接口,返回对应的值即可。
熔断需在配置中添加
feign:
hystrix:
enabled: true
maven引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
//如果不行则将alibaba的ribbon移除
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</exclusion>
</exclusions>
</dependency>