Feign整合Sentinel实现熔断降级处理

Sentinel可以整合Feign进行熔断处理。特别是Hystrix宣布不再维护后,可以轻松的切换成这种方案。整合过程与Hystrix类似

加入alibaba-Sentinel依赖

1
2
3
4
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

yml文件配置启用 Feign 整合 Sentinel 的自动配置

1
2
3
4
# 开启feign对sentinel的支持
feign:
sentinel:
enabled: true

Feign接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@FeignClient(value="user", configuration = FeignExceptionConfig.class, fallbackFactory = UserFeignClientFallbackFactory.class, decode404 = true)
public interface UserFeignClient {

/**
* feign rpc访问远程/users/login接口
* @param username
* @return
*/
@GetMapping(value = "/users/login", params = "username")
LoginAppUser findByUsername(@RequestParam("username") String username);


@GetMapping(value = "/users/mobile", params = "mobile")
LoginAppUser findByMobile(@RequestParam("mobile") String mobile);


@GetMapping(value = "/users", params = "params")
PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params);
}

降级处理类

使用FallbackFactory的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class UserFeignClientFallbackFactory implements FallbackFactory<UserFeignClient> {

private static final Logger log = LoggerFactory.getLogger(UserFeignClientFallbackFactory.class);

@Override
public UserFeignClient create(Throwable throwable) {
return new UserFeignClient() {

@Override
public LoginAppUser findByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
return new LoginAppUser() ;
}

@Override
public LoginAppUser findByMobile(String mobile) {
log.error("通过手机号查询用户异常:{}", mobile, throwable);
return new LoginAppUser();
}

@Override
public PageResult<SysUser> findUsers(Map<String, Object> params) {
log.error("查询用户列表异常:{}");
return null;
}

};
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :