Ribbon 整合Sentinel
发布日期:2021-06-28 15:28:13 浏览次数:3 分类:技术文章

本文共 2595 字,大约阅读时间需要 8 分钟。

 

第一步:加配置
 
<!‐‐
加入
sentinel
‐‐>
<
dependency
>
3
<
groupId
>
com
.
alibaba
.
cloud
</
groupId
>
4
<
artifactId
>
spring
cloud
starter
alibaba
sentinel
</
artifactId
>
5
</
dependency
>
6
7
8
<!‐‐
加入
actuator
‐‐>
9
<
dependency
>
10
<
groupId
>
org
.
springframework
.
boot
</
groupId
>
11
<
artifactId
>
spring
boot
starter
actuator
</
artifactId
>
12
</
dependency
>
13
14
<!‐‐
加入
ribbon
‐‐>
15
<
dependency
>
16
<
groupId
>
org
.
springframework
.
cloud
</
groupId
>
17
<
artifactId
>
spring
cloud
starter
netflix
ribbon
</
artifactId
>
18
</
dependency
>
第二步:加注解(在我们的RestTemplate组件上添加
@SentinelRestTemplate注解)
并且我们可以通过在
@SentinelRestTemplate 同样的可以指定我们的
blockHandlerClass fallbackClass blockHandler fallback 这四个属性
1
@Bean
2
@LoadBalanced
3
@
SentinelRestTemplate
(
4
blockHandler
=
"handleException"
,
blockHandlerClass
=
GlobalExceptionHand
ler
.
class
,
5
fallback
=
"fallback"
,
fallbackClass
=
GlobalExceptionHandler
.
class
6
7
)
8
public
RestTemplate
restTemplate
() {
9
return new
RestTemplate
();
10
}
11
12
13
14
15
*****************
全局异常处理类
16
public class
GlobalExceptionHandler
{
17
18
19
/**
20
*
限流后处理方法
21
*
@param request
22
*
@param body
23
*
@param execution
24
*
@param ex
25
*
@
return
26
*/
27
public static
SentinelClientHttpResponse
handleException
(
HttpRequest re
quest
,
28
byte
[]
body
,
ClientHttpRequestExecution execution
,
BlockException ex
) {
29
30
ProductInfo productInfo
=
new
ProductInfo
();
31
productInfo
.
setProductName
(
"
被限制流量拉
"
);
32
productInfo
.
setProductNo
(
"‐1"
);
33
ObjectMapper objectMapper
=
new
ObjectMapper
();
34
35
try
{
36
return new
SentinelClientHttpResponse
(
objectMapper
.
writeValueAsString
(
p
roductInfo
));
37
}
catch
(
JsonProcessingException e
) {
38
e
.
printStackTrace
();
39
return null
;
40
}
41
}
42
43
/**
44
*
熔断后处理的方法
45
*
@param request
46
*
@param body
47
*
@param execution
48
*
@param ex
49
*
@
return
50
*/
51
public static
SentinelClientHttpResponse
fallback
(
HttpRequest request
,
52
byte
[]
body
,
ClientHttpRequestExecution execution
,
BlockException ex
) {
53
ProductInfo productInfo
=
new
ProductInfo
();
54
productInfo
.
setProductName
(
"
被降级拉
"
);
55
productInfo
.
setProductNo
(
"‐1"
);
56
ObjectMapper objectMapper
=
new
ObjectMapper
();
57
58
try
{
59
return new
SentinelClientHttpResponse
(
objectMapper
.
writeValueAsString
(
p
roductInfo
));
60
}
catch
(
JsonProcessingException e
) {
61
e
.
printStackTrace
();
62
return null
;
63
}
64
}
65
}
第三步:添加配置
什么时候关闭:一般在我们的自己测试业务功能是否正常的情况,关闭该配置
1
#
是否开启
@SentinelRestTemplate
注解
2
resttemplate
:
3
sentinel
:
4
enabled
:
true
​​​​​
 
 
参考博文:

转载地址:https://blog.csdn.net/xiamaocheng/article/details/104561030 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:高性能Mysql 学习笔记
下一篇:Java 不同数据结构之间的比较

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月09日 01时08分04秒