基于redis和mysql分布式锁的实现

更新时间:2023-06-25 18:15:33 阅读: 评论:0

基于redis和mysql分布式锁的实现基于Redis锁实现
实体
⽤于记录锁执⾏情况
package;
import Data;
import Accessors;
import Date;
@Data
@Accessors(chain =true)
public class TaskBo {
private String id;
private String name;
private String systemInfo;
private String redisException;
private String mysqlException;
private String otherException;
private Date  createTime;
/**
*  3:获取redis锁失败
人力资源述职报告*  4:获取mysql锁失败
*  1:获取redis锁成功
*  2获取mysql锁成功
*  5:释放redis锁失败
*  6:释放mysql锁失败
*  7:释放redis锁成功
*  8: 释放mysql锁成功
*/
private String status;
public static void main(String[] args){
try{
Integer j=null;
int i=1/j;
}catch(Exception e){
System.out.String());
}
}
}
基于springboot redis tIfAbnt()⽅法的扩展
import Autowired;
import DataAccessException;
import RedisConnection;
import RedisCallback;
import StringRedisTemplate;
import RedisSerializer;
import Component;
import Serializable;
import StandardCharts;
@Component
public class CustomRedisUtil    {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public boolean tIfAbnt(final String key,final Serializable value,final long exptime){
Boolean result =(Boolean) ute(new RedisCallback<Boolean>(){ @Override
public Boolean doInRedis(RedisConnection connection)throws DataAccessException {                RedisSerializer valueSerializer = ValueSerializer();
RedisSerializer keySerializer = KeySerializer();
Object obj = ute("t", keySerializer.rialize(key),
valueSerializer.rialize(value),
三倍的英文"NX".getBytes(StandardCharts.UTF_8),
"EX".getBytes(StandardCharts.UTF_8),
String.valueOf(exptime).getBytes(StandardCharts.UTF_8));
return obj !=null;
}
});
return result;
}
}
redis获取锁与释放锁的类
import Slf4j;
import Autowired;
import StringRedisTemplate;
import Component;
import UUID;
/**
*  任务开始结束时间保存任务记录以及异常,
九宫格口诀*/
@Slf4j
@Component
public class RedisDistribute {
@Autowired
private CustomRedisUtil redisUtil;
@Autowired
private StringRedisTemplate stringRedisTemplate;
给母亲的生日礼物
/**
*
*
* @param lockName 锁名称
* @param acquireTimeout redis重试时间(这个参数可以不⽤当去掉while循环和睡眠的时候)    * @param expireTime redis过期时间
* @return
*/
public String lockWithTimeOut(String lockName,long acquireTimeout,long expireTime){
String retIdentifier=null;
String identifier= UUID.randomUUID().toString();
String lockKey="lock:"+lockName;
int expire=(int)expireTime/1000;
long end=System.currentTimeMillis()+acquireTimeout;
while(System.currentTimeMillis()<end){
if(redisUtil.tIfAbnt(lockKey,identifier,expire)){
retIdentifier=identifier;
return retIdentifier;
}
try{
Thread.sleep(10*1000);
}catch(InterruptedException interruptedException){
Thread.currentThread().interrupt();
}
}
return retIdentifier;
}
/**
*  释放锁如果上⾯redis添加了失效时间,其实锁也就不需要主动释放了,不过也可以主动释放    * @param lockName
* @param identify
* @return
*/
public boolean releaLock(String lockName,String identify){
String lockKey="lock:"+lockName;
boolean retFlag=fal;
stringRedisTemplate.watch(lockKey);
while(true){
if(identify.equals(stringRedisTemplate.opsForValue().get(lockKey))){
stringRedisTemplate.delete(lockKey);
retFlag=true;
}
stringRedisTemplate.unwatch();
break;
}
return retFlag;
}
}
mysql锁
package;
import SystemUtils;
import Data;
import Date;
/**
* 数据库分布式锁 khzsx_lock
*/
@Data
public class LockBo {
public final static String LOCKED_STATUS ="1";
public final static String UNLOCKED_STATUS ="0";
private String id;
/**
为什么来我们公司* 保证lockname唯⼀加主键是⼀种办法
*/
private String lockName;
private String  expireTime;
private String status;
public LockBo(String lockName, String expireTime, String status){
this.id= CompanyTransNo();
this.lockName = lockName;
this.status = status;
}
}
/
/mapper 接⼝
package;
import LockBo;
import Mapper;
@Mapper
public interface LockMapper {
LockBo findByLockName(String lockName);
int deleteByLockName(String lockName);
int updateByLockName(String lockName);
int saveLock(LockBo lockBo);
}
/
/l⽂件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN""mybatis/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.picclife.authen.system.mapper.LockMapper">
<lect id="findByLockName" resultType="cn.picclife.authen.system.bean.bo.LockBo">
SELECT id as id, lock_name as lockName,expire_time as expireTime,status as status
FROM khzsx_lock WHERE  lock_name= #{lockName} LIMIT 1for update;
</lect>
<delete id="deleteByLockName" parameterType="string">
DELETE FROM khzsx_lock WHERE lock_name=#{lockName}
</delete>
<update id="updateByLockName" parameterType="string">
<!--DELETE FROM khzsx_lock WHERE lock_name=#{lockName}-->
update  khzsx_lock
<t>
<if test="status!=null and status!='' ">
status ='0'
</if>
</t>
WHERE    lock_name=#{lockName}
</update>
<inrt id="saveLock" parameterType="cn.picclife.authen.system.bean.bo.LockBo">
INSERT INTO khzsx_lock
(
聘用书
(
id,
lock_name,
expire_time,
status
)
values (
#{id},
#{lockName},
#{expireTime},
#{status}
)
on duplicate key update id=id
</inrt>
</mapper>
实现mysql锁
package;
四季教案import DateUtil;
import LockBo;
import LockMapper;
import StringUtils;
import$Factory;
import Autowired;
import Component;
import Transactional;
import Calendar;
import Date;
import Objects;
@Component
public class SqlDistribute {
@Autowired
private LockMapper lockMapper;
@Transactional
public String lock(String lockName,Integer expiredSeconds){
if(StringUtils.isEmpty(lockName)){
throw new NullPointerException();
}
LockBo lockBo=lockMapper.findByLockName(lockName);
/** try{
Thread.sleep(1*1000);
}catch (InterruptedException interruptedException){
Thread.currentThread().interrupt();
}**/
if(Objects.isNull(lockBo)){
lockBo=new LockBo(lockName, DateUtil.parDateToStr(this.addSeconds(new Date(),expiredSeconds),DateUtil.DATE_TIME_FORMAT_YYYY_M M_DD_HH_MI_SS),LockBo.LOCKED_STATUS);
//此处保证lockname 唯⼀
if(lockMapper.saveLock(lockBo)>0){
LockName();
}
}
el{
Status()==LockBo.UNLOCKED_STATUS&&DateUtil.ExpireTime(),DateUtil.DATE_TIME_FORMAT_YYYY_M M_DD_HH_MI_SS).after(new Date())){
return null;
}
String expiredTime = ExpireTime();
Date now =new Date();
if(DateUtil.parStrToDate(expiredTime,DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS).before(now)){千千阙歌c调吉他谱

本文发布于:2023-06-25 18:15:33,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1038050.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:时间   任务   释放
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图