docs/Spring全家桶/SpringCloudAlibaba/SpringCloudAlibabaSentinel.md
Spring Cloud Alibaba ṩһվʽSentinel Ϊ֮һ۶һϵзܣĽ÷ϸܡ
Уͷ֮ȶԱԽԽҪ Sentinel Ϊ㣬ơ۶Ͻϵͳرȶάȱȶԡ
Sentinel:
Sentinel̨һĿ̨Ӧãʵʱ鿴ԴؼȺԴܣṩһϵеĹܣعȵȡ
ȴӹSentinelصsentinel-dashboard-1.6.3.jarļصַgithub.com/alibaba/Sen
ɺSentinel̨
java -jar sentinel-dashboard-1.6.3.jar
ƴ
sentinelͨµַԽзʣhttp://localhost:8080Ǵһsentinel-serviceģ飬ʾSentinel۶ܡ
<dependency>
<groupId>com.alibaba.cloud</groupId>
spring-cloud-starter-alibaba-nacos-discovery
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
spring-cloud-starter-alibaba-sentinel
</dependency>
ƴ
server:
port: 8401
spring:
application:
name: sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacosַ
sentinel:
transport:
dashboard: localhost:8080 #sentinel dashboardַ
port: 8719
service-url:
user-service: http://nacos-user-service
management:
endpoints:
web:
exposure:
include: '*'
ƴ
Sentinel Starter ĬΪе HTTP ṩ㣬Ҳͨʹ@SentinelResourceԶһЩΪ
ڲ۶Ϻܡ
/**
*
* Created by macro on 2019/11/7.
*/
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/**
* ԴҪָ
*/
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult("Դ", 200);
}
/**
* URLĬϵ
*/
@GetMapping("/byUrl")
@SentinelResource(value = "byUrl",blockHandler = "handleException")
public CommonResult byUrl() {
return new CommonResult("url", 200);
}
public CommonResult handleException(BlockException exception){
return new CommonResult(exception.getClass().getCanonicalName(),200);
}
}
ƴ
ǿԸ@SentinelResourceעжvalueԴƣҪָ
عSentinel̨ãʹNacosעģNacossentinel-service
SentinelõعҪȷ½ӿڣSentinel̨вŻжӦϢȷ¸ýӿڣhttp://localhost:8401/rateLimit/byResource
Sentinel̨ع@SentinelResourceעvalueֵ
ǻͨʵURL᷵ĬϵϢ
ǿԶͨõȻ@SentinelResourceָ
/**
* Created by macro on 2019/11/7.
*/
public class CustomBlockHandler {
public CommonResult handleException(BlockException exception){
return new CommonResult("ԶϢ",200);
}
}
ƴ
/**
*
* Created by macro on 2019/11/7.
*/
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/**
* Զͨõ
*/
@GetMapping("/customBlockHandler")
@SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
public CommonResult blockHandler() {
return new CommonResult("ɹ", 200);
}
}
ƴ
Sentinel ֶ֧ԷýбԹӦý۶ϲʹRestTemplatenacos-user-serviceṩĽӿʾ¸ùܡ
/**
* Created by macro on 2019/8/29.
*/
@Configuration
public class RibbonConfig {
@Bean
@SentinelRestTemplate
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
ƴ
/**
* ۶Ϲ
* Created by macro on 2019/11/7.
*/
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {
private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.user-service}")
private String userServiceUrl;
@RequestMapping("/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handleFallback")
public CommonResult fallback(@PathVariable Long id) {
return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
}
@RequestMapping("/fallbackException/{id}")
@SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
public CommonResult fallbackException(@PathVariable Long id) {
if (id == 1) {
throw new IndexOutOfBoundsException();
} else if (id == 2) {
throw new NullPointerException();
}
return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
}
public CommonResult handleFallback(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"",200);
}
public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
User defaultUser = new User(-2L, "defaultUser2", "123456");
return new CommonResult<>(defaultUser,"",200);
}
}
ƴ
nacos-user-servicesentinel-service
Dzûnacos-user-serviceжidΪ4ûз½ӿڻ᷵طhttp://localhost:8401/breaker/fallback/4
{
"data": {
"id": -1,
"username": "defaultUser",
"password": "123456"
},
"message": "",
"code": 200
}
ƴ
SentinelҲFeignʹFeignзʱҲʹ۶ϡ
<dependency>
<groupId>org.springframework.cloud</groupId>
spring-cloud-starter-openfeign
</dependency>
ƴ
feign:
sentinel:
enabled: true #sentinelfeign֧
ƴ
Ӧ@EnableFeignClientsFeignĹܣ
һUserServiceӿڣڶnacos-user-serviceĵã
/**
* Created by macro on 2019/9/5.
*/
@FeignClient(value = "nacos-user-service",fallback = UserFallbackService.class)
public interface UserService {
@PostMapping("/user/create")
CommonResult create(@RequestBody User user);
@GetMapping("/user/{id}")
CommonResult<User> getUser(@PathVariable Long id);
@GetMapping("/user/getByUsername")
CommonResult<User> getByUsername(@RequestParam String username);
@PostMapping("/user/update")
CommonResult update(@RequestBody User user);
@PostMapping("/user/delete/{id}")
CommonResult delete(@PathVariable Long id);
}
ƴ
/**
* Created by macro on 2019/9/5.
*/
@Component
public class UserFallbackService implements UserService {
@Override
public CommonResult create(User user) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"",200);
}
@Override
public CommonResult<User> getUser(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"",200);
}
@Override
public CommonResult<User> getByUsername(String username) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"",200);
}
@Override
public CommonResult update(User user) {
return new CommonResult("ʧܣ",500);
}
@Override
public CommonResult delete(Long id) {
return new CommonResult("ʧܣ",500);
}
}
ƴ
/**
* Created by macro on 2019/8/29.
*/
@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public CommonResult getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping("/getByUsername")
public CommonResult getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}
@PostMapping("/create")
public CommonResult create(@RequestBody User user) {
return userService.create(user);
}
@PostMapping("/update")
public CommonResult update(@RequestBody User user) {
return userService.update(user);
}
@PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
return userService.delete(id);
}
}
ƴ
{
"data": {
"id": -1,
"username": "defaultUser",
"password": "123456"
},
"message": "",
"code": 200
}
ƴ
Ĭ£Sentinel̨ùʱ̨ʽͨAPIͻ˲ֱӸµڴСһӦãʧǽνùг־ûԴ洢NacosΪ
ֱĴĽ͵ͻˣ
Sentinel̨ҲȥȡϢ
<dependency>
<groupId>com.alibaba.csp</groupId>
sentinel-datasource-nacos
</dependency>
ƴ
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
ƴ
[
{
"resource": "/rateLimit/byUrl",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
ƴ
زͣ
Sentinel̨Ѿ
Spring Cloud Alibaba ٷĵgithub.com/alibaba/spr
springcloud-learning
nacos-user-service -- עᵽnacosṩUserCRUDӿڵķ
sentinel-service -- sentinelܲԷ
ƴ
ߣMacroZheng ӣhttps://juejin.cn/post/6844903999876022279 Դϡ ȨСҵתϵȨҵתע
https://lijunyi.xyz/docs/SpringCloud/SpringCloud.html#_2-2-x-%E5%88%86%E6%94%AF https://mp.weixin.qq.com/s/2jeovmj77O9Ux96v3A0NtA https://juejin.cn/post/6931922457741770760 https://github.com/D2C-Cai/herring http://c.biancheng.net/springcloud