Redisson实现分布式锁 --简单
maven pom.xml 引入依赖包
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>2.9.3</version>
</dependency>
spring bean 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:redisson="http://redisson.org/schema/redisson"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://redisson.org/schema/redisson
http://redisson.org/schema/redisson/redisson.xsd"
default-autowire="byName">
<!--redission 相关配置 请勿改动 -->
<redisson:client id="redissonClient">
<redisson:single-server address="redis://${redis.ip}:${redis.port}" />
</redisson:client>
</beans>
伪代码:
import org.apache.log4j.Logger; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class RedissonLockImpl{ private static final Logger logger = Logger.getLogger(RedissonLockImp.class); @Autowired private RedissonClient redissonClient; private static final String LOCK_INVOICE_PREFIX = "yonyou_invoice_lock_"; public void lockDH(JSONObject param){ /** redission分布式锁,防止并发操作同一订单开具发票 */ RLock lock = redissonClient.getLock(LOCK_INVOICE_PREFIX + data.getTenancy_id() + "_" + param.optString("DH")); try{ boolean flag = lock.tryLock(2, TimeUnit.MINUTES); if (flag) { //查库判断是否已经取消 validate = issueElectronicInvoiceValid(data,result,param); if(!validate) { return; } //组装h5 URL reqUrl = buildUrl(data,result,param); if(StringUtils.isBlank(reqUrl)) { result.setMsg("获取开票地址失败:\n"+result.getMsg()); return; } logger.info(reqUrl); } else { logger.info("未获取到锁业务结束.."); } }catch(Exception e){ logger.error("生成电子发票过程异常:", e); throw new Exception(e.getMessage()); }finally{ lock.unlock(); } } }