SpringCloudAlibaba-整合sentinel(四)
目录地址:
这里只关注代码部分,至于sentinel服务UI的实用,后面可以补上
这里做一个改造:
因为sentinel可以和openfeign结合使用,为微服务做熔断降级;
为了方便微服务之间的调用,把远程调用接口移动到api模块;
所以把order中的openfeign和loadbalancer依赖,放到api的pom中,并且把order中Remote接口,移动到api中;后续order只需要引入api的依赖,调用api中的接口即可
1.在api中引入sentinel和openfeign
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--loadbalancer-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2.把接口从order转移到api,并修改
@FeignClient(name="my-user", fallbackFactory = UserServiceFactory.class)
public interface RemoteUserService {
@RequestMapping("/user/listAll")
public List<User> listAll();
@GetMapping("/user/getById")
public User getById(@RequestParam("id") Integer id);
}
api模块,添加UserServiceFactory类
@Component
public class UserServiceFactory implements FallbackFactory<RemoteUserService> {
@Override
public RemoteUserService create(Throwable cause) {
return new RemoteUserService() {
@Override
public List<User> listAll() {
return null;
}
@Override
public User getById(Integer id) {
System.out.println("user服务异常");
return null;
}
};
}
}
3.注意要把UserServiceFactory放到META-INF/spring.factories文件中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.api.remote.fallbackFactory.UserServiceFactory,\
com.test.api.remote.fallbackFactory.ProductServiceFactory
4.order引入api依赖,并在启动类添加注解,扫描feignClient接口
@EnableFeignClients(basePackages = {"com.test.api.remote"})
5.order的配置文件添加
feign:
sentinel:
enabled: true
6.重启服务,访问接口,正常访问
此时停止user服务,再次访问order接口,返回null,后台日志打印“user服务异常”
原文地址:https://blog.csdn.net/zifengye520/article/details/137604315
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!