在Java业务逻辑中,如何利⽤redis防⽌重复请求后插⼊多条
相同数据
如果⽣成⽐如WX00000001并且⾃动递增的ID时,如果多次、多客户端同时请求,会出现重复⽣成的情况。
解决⽅案如下:
@Resource
private RedisGenerateIdUtil redisGenerateIdUtil;//⽣成⾃增id
private static final String PRODUCT_GENERATE_ID = "ID:AUTO:INCREMENT";
卖火柴的小女孩故事
诚惶诚恐造句private Object lockObj = new Object();
String preffix = "WX";
//redis获取值
String wxIdKey = WxIdKey(PRODUCT_GENERATE_ID);
Long incr = Incr(wxIdKey);
if(incr == null){
//防⽌key过期出现重复数据
synchronized (lockObj) {
//查询上⼀个id
String id = wxMapper.lectCode();
int suffix = 00000000;
if (StringUtils.isNotEmpty(code)) {
String[] split = code.split(preffix);
String suffixStr = split[1];
Integer suffixInt = Integer.valueOf(suffixStr);
suffix = suffixInt + 1;
}
incr = new Long(suffix);
十瀑峡
redisGenerateIdUtil.tIncr(wxIdKey, suffix);银行竞聘演讲稿
}
}
String id = preffix + incr;四颗糖的故事
⼯具类内容如下
/**
* @Description redis⽣成分布式id,⽀持long型⾃增
*/
现货白银开户
@Configuration
public class RedisGenerateIdUtil {
private final RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisGenerateIdUtil(RedisTemplate<String, Object> redisTemplate){
}
/**
* redis设置初值,暂未设置过期时间
* @param key
* @param value
耽美小说免费
*/
public void tIncr(String key,int value) {
Asrt.hasText(key, "a valid key name is required");
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, ConnectionFactory()); redisAtomicLong.t(value);
//pire(timeout, TimeUnit.SECONDS);
}
/**
* redis获取值,暂未设置过期时间
* @param key
* @return
*/
public Long getIncr(String key){
Asrt.hasText(key, "a valid key name is required");
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, ConnectionFactory()); Long increment = entityIdCounter.incrementAndGet();
//未设置key,默认值为0 incrementAndGet() ⼀次后为1
if(increment == 1){
increment = null;
}
//pire(timeout, TimeUnit.SECONDS);外国钱币
return increment;
}
}