读者福利
由于篇幅过长,就不展示所有面试题了,感兴趣的小伙伴
更多笔记分享
创建CustomBlockHandler类用于自定义限流处理逻辑:
public class CustomBlockHandler {
public Result handleException(BlockException exception) {
return new Result(“自定义限流信息”, 200);
}
}
在RateLimitController中使用自定义限流处理逻辑:
@RestController
@RequestMapping(“/rateLimit”)
public class RateLimitController {
/**
- 自定义通用的限流处理逻辑
*/
@GetMapping(“/customBlockHandler”)
@SentinelResource(value = “customBlockHandler”, blockHandler = “handleException”, blockHandlerClass = CustomBlockHandler.class)
public Result blockHandler() {
return new Result(“限流成功”, 200);
}
}
Sentinel 支持对服务间调用进行保护,对故障应用进行熔断操作,这里我们使用RestTemplate来调用nacos-user-service服务所提供的接口来演示下该功能。
首先我们需要使用@SentinelRestTemplate来包装下RestTemplate实例:
@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
添加CircleBreakerController类,定义对nacos-user-service提供接口的调用:
@RestController
@RequestMapping(“/breaker”)
public class CircleBreakerController {
private static final Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
@Autowired
private RestTemplate restTemplate;
@Value(“${service-url.user-service}”)
private String userServiceUrl;
@GetMapping(“/fallback/{id}”)
// @SentinelResource(value = “fallback”, fallback = “handleFallback”)
public Result fallback(@PathVariable Long id) {
Result forObject = restTemplate.getForObject(userServiceUrl + “/user/{1}”, Result.class, id);
System.out.println(forObject);
return forObject;
}
@GetMapping(“/fallbackException/{id}”)
@SentinelResource(value = “fallbackException”, fallback = “handleFallback2”, exceptionsToIgnore = {NullPointerException.class})
public Result fallbackException(@PathVariable Long id) {
if (id == 1) {
throw new IndexOutOfBoundsException();
} else if (id == 2) {
throw new NullPointerException();
}
return restTemplate.getForObject(userServiceUrl + “/user/{1}”, Result.class, id);
}
public Result handleFallback(Long id) {
return new Result(“服务降级返回”, 200);
}
public Result handleFallback2(Long id, Throwable e) {
LOGGER.error(“handleFallback2 id:{},throwable class:{}”, id, e.getClass());
return new Result(“服务降级返回”, 200);
}
}
启动nacos-user-service和sentinel-service服务:
由于我们并没有在nacos-user-service中定义id为4的用户,所有访问如下接口会返回服务降级结果:http://localhost:8401/breaker/fallback/4
{
“data”: null,
“message”: “服务降级返回”,
“code”: 200
}
由于我们使用了exceptionsToIgnore参数忽略了NullPointerException,所以我们访问接口报空指针时不会发生服务降级:http://localhost:8401/breaker/fallbackException/2
Sentinel也适配了Feign组件,我们使用Feign来进行服务间调用时,也可以使用它来进行熔断。
首先我们需要在pom.xml中添加Feign相关依赖:
org.springframework.cloud
spring-cloud-starter-openfeign
在application.yml中打开Sentinel对Feign的支持:
打开sentinel对feign的支持
feign:
sentinel:
enabled: true
在应用启动类上添加@EnableFeignClients启动Feign的功能;
创建一个UserService接口,用于定义对nacos-user-service服务的调用:
@FeignClient(value = “nacos-user-service”, fallback = UserFallbackService.class)
public interface UserService {
@PostMapping(“/user/insert”)
Result insert(@RequestBody User user);
@GetMapping(“/user/{id}”)
Result getUser(@PathVariable Long id);
@GetMapping(“/user/listUsersByIds”)
Result<List> listUsersByIds(@RequestParam List ids);
@GetMapping(“/user/getByUsername”)
Result getByUsername(@RequestParam String username);
@PostMapping(“/user/update”)
Result update(@RequestBody User user);
@PostMapping(“/user/delete/{id}”)
Result delete(@PathVariable Long id);
}
创建UserFallbackService类实现UserService接口,用于处理服务降级逻辑:
@Component
public class UserFallbackService implements UserService {
@Override
public Result insert(User user) {
return new Result(“调用失败,服务被降级”,500);
}
@Override
public Result getUser(Long id) {
return new Result(“调用失败,服务被降级”,500);
}
@Override
public Result<List> listUsersByIds(List ids) {
return new Result(“调用失败,服务被降级”,500);
}
@Override
public Result getByUsername(String username) {
return new Result(“调用失败,服务被降级”,500);
}
@Override
public Result update(User user) {
return new Result(“调用失败,服务被降级”,500);
}
@Override
public Result delete(Long id) {
return new Result(“调用失败,服务被降级”,500);
}
}
在UserFeignController中使用UserService通过Feign调用nacos-user-service服务中的接口:
@RestController
@RequestMapping(“/user”)
public class UserFeignController {
@Autowired
private UserService userService;
@PostMapping(“/insert”)
public Result insert(@RequestBody User user) {
return userService.insert(user);
}
@GetMapping(“/{id}”)
public Result getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping(“/listUsersByIds”)
public Result<List> listUsersByIds(@RequestParam List ids) {
return userService.listUsersByIds(ids);
}
@GetMapping(“/getByUsername”)
public Result getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}
@PostMapping(“/update”)
public Result update(@RequestBody User user) {
return userService.update(user);
}
@PostMapping(“/delete/{id}”)
public Result delete(@PathVariable Long id) {
return userService.delete(id);
}
}
在启动类SentinelServiceApplication添加@EnableFeignClients注解
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class SentinelServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SentinelServiceApplication.class, args);
}
}
调用如下接口会发生服务降级,返回服务降级处理信息:http://localhost:8401/user/4
{
“data”: null,
“message”: “调用失败,服务被降级”,
“code”: 500
}
默认情况下,当我们在Sentinel控制台中配置规则时,控制台推送规则方式是通过API将规则推送至客户端并直接更新到内存中。一旦我们重启应用,规则将消失。下面我们介绍下如何将配置规则进行持久化,以存储到Nacos为例。
原理示意图
首先我们直接在配置中心创建规则,配置中心将规则推送到客户端;
Sentinel控制台也从配置中心去获取配置信息。
功能演示
先在pom.xml中添加相关依赖:
com.alibaba.csp
sentinel-datasource-nacos
修改application.yml配置文件,添加Nacos数据源配置:
spring:
application:
name: sentinel-service
cloud:
nacos:
配置Nacos地址
server-addr: http://localhost:8848
sentinel:
transport:
配置Sentinel dashborad地址
dashboard: http://localhost:8080
port: 8719
添加Nacos数据源配置
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
在Nacos中添加配置:
添加配置信息如下:
[
{
“resource”: “/rateLimit/byUrl”,
“limitApp”: “default”,
“grade”: 1,
“count”: 1,
“strategy”: 0,
“controlBehavior”: 0,
“clusterMode”: false
}
]
相关参数解释:
-
resource:资源名称;
-
limitApp:来源应用;
-
grade:阈值类型,0表示线程数,1表示QPS;
-
count:单机阈值;
-
strategy:流控模式,0表示直接,1表示关联,2表示链路;
-
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
-
clusterMode:是否集群。
发现Sentinel控制台已经有了如下限流规则:
总结
如果你选择了IT行业并坚定的走下去,这个方向肯定是没有一丝问题的,这是个高薪行业,但是高薪是凭自己的努力学习获取来的,这次我把P8大佬用过的一些学习笔记(pdf)都整理在本文中了
《Java中高级核心知识全面解析》
小米商场项目实战,别再担心面试没有实战项目:
Behavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
- clusterMode:是否集群。
发现Sentinel控制台已经有了如下限流规则:
总结
如果你选择了IT行业并坚定的走下去,这个方向肯定是没有一丝问题的,这是个高薪行业,但是高薪是凭自己的努力学习获取来的,这次我把P8大佬用过的一些学习笔记(pdf)都整理在本文中了
《Java中高级核心知识全面解析》
[外链图片转存中…(img-DxjpcaIW-1715465860806)]
小米商场项目实战,别再担心面试没有实战项目:
[外链图片转存中…(img-wIsErpEP-1715465860807)]