【SpringCloud】06-Sentinel
1. 雪崩问题
一个微服务出现问题导致一系列微服务都不可以正常工作。
服务保护方案:
- 请求限流。
- 线程隔离。
- 服务熔断
2. Sentinel
- 启动Sentinel
java -Dserver.port=8090 -Dcsp.sentinel.dashboard.server=localhost:8090 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
- 依赖
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
- 配置
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8090
http-method-specify: true # 将请求方式也作为簇点链路
簇点链路: Controller中的Rest接口
3. Fallback
- 配置openfeign使之能够成为簇点链路
feign:
okhttp:
enabled: true # 开启OKHttp功能
sentinel: # 让feign可以成为簇点链路
enabled: true
- 设置FallbackFactory
package com.hmall.api.client.fallback;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.common.utils.CollUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import java.util.Collection;
import java.util.List;
@Slf4j
public class ItemClientFallbackFactory implements FallbackFactory<ItemClient> {
@Override
public ItemClient create(Throwable cause) {
return new ItemClient() {
@Override
public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
log.info("查询商品失败!", cause);
return CollUtils.emptyList();
}
@Override
public void deductStock(List<OrderDetailDTO> items) {
log.info("扣减商品库存失败!", cause);
throw new RuntimeException(cause);
}
};
}
}
- 注册Bean
package com.hmall.api.config;
import com.hmall.api.client.fallback.ItemClientFallbackFactory;
import com.hmall.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
public class DefaultFeignConfig {
@Bean
public Logger.Level feignLogLevel() {
return Logger.Level.FULL;
}
@Bean
public RequestInterceptor userInfoRequestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
Long userId = UserContext.getUser();
if (userId!=null) {
requestTemplate.header("user-info", userId.toString());
}
}
};
}
@Bean
public ItemClientFallbackFactory itemClientFallbackFactory() {
return new ItemClientFallbackFactory();
}
}
- 配置Bean
@FeignClient(value = "item-service", fallbackFactory = ItemClientFallbackFactory.class)
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
@PutMapping("/items/stock/deduct")
void deductStock(@RequestBody List<OrderDetailDTO> items);
}
4. 熔断
拒绝发送请求给故障的微服务