分布式Id获取
@DubboService(version="1.0.0",group="distributed-uuid-server")
public class DistributedServiceImpl implements DistributedService{
@Autowired
private Snowflakeconfig snowflakeConfig;
Map<String,SnowFlake> snowFlakeHandlerMap = new ConcurrentHashMap<>();
@Override
public long nextId(final long datacenterId,final long machineId){
final long sdatacenterId = datacenterId;
final long smachineId = machineId;
final String handler = sdatacenterId+"_"+smachineId;
SnowFlake snowFlake;
if(snowFlakeHandlerMap.containsKey(handler)){
snowFlake = snowFlakeHandlerMap.get(handler);
return snowFlake;
}else{
snowFlake = new SnowFlake(datacenterId,machineId);
snowFlakeHandlerMap.putifAbsent(handler,snowFlake);
return snowFLake.nextId();
}
}
@Override
public long nextId(){
List<SnowFlakeInfo> config = snowFlakeCongig.getConfig();
String localAddress = NetUtils.getLocalAddress();
SnowFlakeInfo snowFlakeInfo = config.stream().filter(s->Objects.equals(s.getIp(),localAddress)).findFirst().orElse(null);
long dataCenterId = Optional.ofNullable(snowFlakeInfo).map(SnowFlakeINfo::getDatacenterId).orElse(0L);
long machineId = Optional.ofNullable(snowFlakeInfo).map(SnowFlakeInfo::getMachineId).orElse(0L);
return nextId(dataCenterId,machineId);
}
}
消费者服务
@RestController("/good")
public class GoodController{
@DubboReference(version="1.0.0",group="idempotent-design-user-server",retries=4,timeout=1)
private GoodService goodService;
@DubboReference
private DistributeService distributeService;
@Autowired
private NacosConfig nacosConfig;
@PostMapping("/updateGoodsNum")
@ResponseBody
public DefaultResult<GoodsDTO> updateGoodsNum(@RequestPatam Stirng goodId){
long uuid = distributeService.nextId(7,8);
GoodsServiceRequest<ProductBo> request
= new GoodsServiceRequest<>();
ProductBo b0 = new ProductBo();
bo.setGoodsId(Long.valueOf(goodId));
request.setRequestData(bo);
if(nacosConfig.isMideng()){
request.setUuid(uuid+"");
}
return goodService.updateGoodNum(request);
}
}
服务提供
@DubboService(version="1.0.0",group="xxx")
public class GoodsServiceImpl implements GoodService{
...
if(!StringUtils.isEmpty(goodsServiceRequest.getUuid())){
long uuid = Long.parseLong(goodServiceRequest.getUuid());
if(null != redisTemplate.opsForValue().get(uuid)){
result.setData(new GoodDTO());
result.setMessage("asdfs");
return result;
}else{
redisTemplate.opsForValue().set(uuid,true,2,TimeUnit.SECONDS);
}
}
}