一、雪崩问题
二、雪崩-解决方案(服务保护方案)
请求限流:
线程隔离:
服务熔断:
服务保护组件:
三、Sentinel
引入依赖:
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
server:
port: 8082
feign:
okhttp:
enabled: true #配置连接池开关
swagger:
title: "黑马商城购物车服务接口文档"
package: "com.hmall.cart.controller"
description: "购物车服务接口"
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8090 #sentinel控制台地址
簇点链路:
Endpoint==Controller里的各种路径
请求限流:
QPS:每秒钟请求的数量
线程隔离:
fallback:
案例-给FeignClient添加Fallback逻辑:
package com.hmall.api.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.error("查询商品失败!",cause);
//查询不到返回一个空集合
return CollUtils.emptyList();
}
@Override
public void deductStock(List<OrderDetailDTO> items) {
log.error("扣减商品库存失败!",cause);
throw new RuntimeException(cause);
}
};
}
}
package com.hmall.api.config;
import com.hmall.api.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对象
@Bean
public Logger.Level feignLoggerLevel(){
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();
}
}
服务熔断:
断路器:
四、分布式事务
Seata:
Seata架构:
部署TC服务:
docker run --name seata \
-p 8099:8099 \
-p 7099:7099 \
-e SEATA_IP=192.168.50.129 \ #自己的IP地址
-v ./seata:/seata-server/resources \
--privileged=true \
--network hmall \ #确保和nacos mysql在一个网络下
-d \
seataio/seata-server:1.5.2
微服务继承Seata:
通过nacos共享配置:
seata:
registry: # TC服务注册中心的配置,微服务根据这些信息去注册中心获取tc服务地址
type: nacos # 注册中心类型 nacos
nacos:
server-addr: 192.168.50.129:8848 # nacos地址
namespace: "" # namespace,默认为空
group: DEFAULT_GROUP # 分组,默认是DEFAULT_GROUP
application: seata-server # seata服务名称
username: nacos
password: nacos
tx-service-group: hmall # 事务组名称
service:
vgroup-mapping: # 事务组与tc集群的映射关系
hmall: "default"
XA模式:
实现XA模式:
整个事务中其他微服务端的事务因为后续也需要实现事务管理,都需要在对应方法上加上@Transactional
AT模式:
实现AT模式:
AT与XA区别:
追求一致性选XA
追求性能选AT