谷粒商城高级结束(四十八)
325-338 整合链路追踪和sentinel
全部的Java代码已经提交到:https://gitee.com/dalianpai/gulimall
之前的boot和cloud都是高版本,整合的时候有问题,而且高版本在加入actuator后,用JRebel启动也有报错,降低版本和视频中一样的时候,P6spy数据源也有问题,最后就先不用p6spy了。
之前也简单写过博客:https://www.cnblogs.com/dalianpai/p/12286966.html
下面为主要的代码:
/**
* @author WGR
* @create 2020/8/20 -- 21:59
*/
@Configuration
public class SecKillSentinelConfig {
public SecKillSentinelConfig(){
WebCallbackManager.setUrlBlockHandler((request, response, exception) -> {
R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMessage());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(error));
});
}
}
@SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
@Override
public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
// 1.确定当前时间属于那个秒杀场次
long time = new Date().getTime();
try (Entry entry = SphU.entry("seckillSkus")){
Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
for (String key : keys) {
String replace = key.replace("seckill:sessions:", "");
String[] split = replace.split("_");
long start = Long.parseLong(split[0]);
long end = Long.parseLong(split[1]);
if(time >= start && time <= end){
// 2.获取这个秒杀场次的所有商品信息
List<String> range = redisTemplate.opsForList().range(key, 0, 100);
BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREDIX);
List<String> list = hashOps.multiGet(range);
if(list != null){
return list.stream().map(item -> {
SecKillSkuRedisTo redisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
return redisTo;
}).collect(Collectors.toList());
}
break;
}
}
}catch (BlockException e){
log.warn("资源被限流:" + e.getMessage());
}
return null;
}
后来sentinel版本要换成1.7.2
/**
* @author WGR
* @create 2020/8/24 -- 12:19
*/
@Configuration
public class SentinelGateWayConfig {
public SentinelGateWayConfig(){
GatewayCallbackManager.setBlockHandler((exchange, t) ->{
// 网关限流了请求 就会回调这个方法
R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMessage());
String errJson = JSON.toJSONString(error);
Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errJson), String.class);
return body;
});
}
}