一、服务发现Nacos配置
(1) Nacos安装
下载地址 https://github.com/alibaba/nacos/releases
本人使用的是1.3.1版本
(2)启动Nacos
双击nacos\bin目录下的startup.cmd
提示这样就启动成功了
控制台地址
http://localhost:8848/nacos/
默认账号密码:nacos
(3)在SpringBoot中引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>${latest.version}</version>
</dependency>
(4)在application.properties中添加配置
spring.cloud.discovery.server-addr=127.0.0.1:8848
#配置服务名称
spring.application.name=service
(5)在启动类中进行写类注解进行nacos注册
@EnableDiscoveryClient
(6)验证结果
进入控制台
二、服务调用Feign配置
前提条件:把互相调用服务在Nacos中进行注册
(1)在SpringBoot引入依赖
<!-- 服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
(2)在调用端的启动类上加注解
@EnableFeignClients
(3) 在调用端 创建interface
3.1 在调用端创建一个包
3.2 包里创建一个interface,加上注解@Component @FeignClient(“被调用的服务名,在nacos控制台能看到”)
如:
@Component
@FeignClient("service-service")
public interface VodClient{
}
3.3 在interface中定义调用方法路径,即被调用的controller方法名和注解
如:
@Component
@FeignClient("service-service")
public interface VodClient{
@DeleMapping("/eduvod/video/removeAlyVideo/{id}") //要完整的路径
public R removeAlyVideo(@PathVariable("id") String id); //@PathVariable一定要有完整的参数名称
}
(4)实现调用
在调用端需要用到方法调用的那个类中,注入刚才创建的interface,然后调用interface中的方法
如:
public xxx xxxService{
@Autowired
private VodClient vodClient;
public R deleteeVideo(String id){
vodClient.removeAlyVideo(id);
}
}
三、熔断器Hystrix配置
(1) 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<!-- hystrix依赖 主要是用@HystrixCommand-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
(2)在调用端配置文件properties中开启熔断器
#开启熔断机制
eign.hystrix.enabled=true
#设置hystrix超时时间,默认1000ms
#hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000
(3)创建对应实现类
在之前服务调用的时候创建interface之后,还需要创建interface对应的实现类,在实现类实现方法,实现出错了输出内容
如:
@Component
public calss vodFileDegradeFeignClient implements VodClient{
@Override
public R removeAlyVideo(String id){
return null;
}
}
(4)在interface上面添加注解和属性
@FeignClient(name="被调用的服务名,在nacos控制台能看到",fallback=VodFileDegradeFeignClient.calss)
//实现类名称
如:
@Component
@FeignClient("service-service",fallback=VodFileDegradeFeignClient.calss)
public interface VodClient{
@DeleMapping("/eduvod/video/removeAlyVideo/{id}") //要完整的路径
public R removeAlyVideo(@PathVariable("id") String id); //@PathVariable一定要有完整的参数名称
}
总结
服务发现–Alibaba Nacos
服务调用–Netfilx Feign
熔断器–Netfilx Hystrix