SpringCloudAlibaba-整合sentinel(四)

目录地址:

SpringCloudAlibaba整合-CSDN博客

这里只关注代码部分,至于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服务异常”

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值