redis實(shí)現(xiàn)分布式鎖實(shí)例詳解
1、業(yè)務(wù)場(chǎng)景引入
模擬一個(gè)電商系統(tǒng),服務(wù)器分布式部署,系統(tǒng)中有一個(gè)用戶下訂單的接口,用戶下訂單之前需要獲取分布式鎖,然后去檢查一下庫(kù)存,確保庫(kù)存足夠了才會(huì)給用戶下單,然后釋放鎖。
由于系統(tǒng)有一定的并發(fā),所以會(huì)預(yù)先將商品的庫(kù)存保存在redis中,用戶下單的時(shí)候會(huì)更新redis的庫(kù)存。
2、基礎(chǔ)環(huán)境準(zhǔn)備
2.1.準(zhǔn)備庫(kù)存數(shù)據(jù)庫(kù)
-- ----------------------------
-- Table structure for t_goods
-- ----------------------------
DROP TABLE IF EXISTS `t_goods`;
CREATE TABLE `t_goods` (
`goods_id` int(11) NOT NULL AUTO_INCREMENT,
`goods_name` varchar(255) DEFAULT NULL,
`goods_price` decimal(10,2) DEFAULT NULL,
`goods_stock` int(11) DEFAULT NULL,
`goods_img` varchar(255) DEFAULT NULL,
PRIMARY KEY (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_goods
-- ----------------------------
INSERT INTO `t_goods` VALUES ('1', 'iphone8', '6999.00', '5000', 'img/iphone.jpg');
INSERT INTO `t_goods` VALUES ('2', '小米9', '3000.00', '5000', 'img/rongyao.jpg');
INSERT INTO `t_goods` VALUES ('3', '華為p30', '4000.00', '5000', 'img/huawei.jpg');2.2.創(chuàng)建SpringBoot工程,pom.xml中導(dǎo)入依賴,請(qǐng)注意版本。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springlock.task</groupId>
<artifactId>springlock.task</artifactId>
<version>1.0-SNAPSHOT</version>
<!--導(dǎo)入SpringBoot的父工程 把系統(tǒng)中的版本號(hào)做了一些定義! -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<!--導(dǎo)入SpringBoot的Web場(chǎng)景啟動(dòng)器 Web相關(guān)的包導(dǎo)入!-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--導(dǎo)入MyBatis的場(chǎng)景啟動(dòng)器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<!--SpringBoot單元測(cè)試-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--導(dǎo)入Lombok依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--Spring Data Redis 的啟動(dòng)器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<!--編譯的時(shí)候同時(shí)也把包下面的xml同時(shí)編譯進(jìn)去-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>2.3.application.properties配置文件
# SpringBoot有默認(rèn)的配置,我們可以覆蓋默認(rèn)的配置 server.port=8888 # 配置數(shù)據(jù)的連接信息 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/redislock?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # reids配置 spring.redis.jedis.pool.max-idle=10 spring.redis.jedis.pool.min-idle=5 spring.redis.jedis.pool.maxTotal=15 spring.redis.hostName=192.168.3.28 spring.redis.port=6379
2.4.SpringBoot啟動(dòng)類
/**
* @author swadian
* @date 2022/3/4
* @Version 1.0
* @describetion
*/
@SpringBootApplication
public class SpringLockApplicationApp {
public static void main(String[] args) {
SpringApplication.run(SpringLockApplicationApp.class,args);
}
}2.5.添加Redis的配置類
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Slf4j
@Configuration
public class RedisConfig {
/**
* 1.創(chuàng)建JedisPoolConfig對(duì)象。在該對(duì)象中完成一些鏈接池配置
* @ConfigurationProperties:會(huì)將前綴相同的內(nèi)容創(chuàng)建一個(gè)實(shí)體。
*/
@Bean
@ConfigurationProperties(prefix="spring.redis.jedis.pool")
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig config = new JedisPoolConfig();
log.info("JedisPool默認(rèn)參數(shù)-最大空閑數(shù):{},最小空閑數(shù):{},最大鏈接數(shù):{}",config.getMaxIdle(),config.getMinIdle(),config.getMaxTotal());
return config;
}
/**
* 2.創(chuàng)建JedisConnectionFactory:配置redis鏈接信息
*/
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){
log.info("redis初始化配置-最大空閑數(shù):{},最小空閑數(shù):{},最大鏈接數(shù):{}",config.getMaxIdle(),config.getMinIdle(),config.getMaxTotal());
JedisConnectionFactory factory = new JedisConnectionFactory();
//關(guān)聯(lián)鏈接池的配置對(duì)象
factory.setPoolConfig(config);
return factory;
}
/**
* 3.創(chuàng)建RedisTemplate:用于執(zhí)行Redis操作的方法
*/
@Bean
public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
//關(guān)聯(lián)
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer來(lái)序列化和反序列化redis的value值(默認(rèn)使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
//指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會(huì)跑出異常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
//使用StringRedisSerializer來(lái)序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
//值采用json序列化
template.setValueSerializer(jacksonSeial);
//設(shè)置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
return template;
}
}2.6.pojo層
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Goods {
private String goods_id;
private String goods_name;
private Double goods_price;
private Long goods_stock;
private String goods_img;
}2.7.mapper層
import com.springlock.pojo.Goods;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
@Mapper
public interface GoodsMapper {
/**
* 01-更新商品庫(kù)存
* @param goods
* @return
*/
@Update("update t_goods set goods_stock=#{goods_stock} where goods_id=#{goods_id}")
Integer updateGoodsStock(Goods goods);
/**
* 02-加載商品信息
* @return
*/
@Select("select * from t_goods")
List<Goods> findGoods();
/**
* 03-根據(jù)ID查詢
* @param goodsId
* @return
*/
@Select("select * from t_goods where goods_id=#{goods_id}")
Goods findGoodsById(String goodsId);
}2.8.SpringBoot監(jiān)聽Web啟動(dòng)事件,加載商品數(shù)據(jù)到Redis中
import com.springlock.mapper.GoodsMapper;
import com.springlock.pojo.Goods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
* @author swadian
* @date 2022/3/4
* @Version 1.0
* @describetion ApplicationListener監(jiān)聽器,項(xiàng)目啟動(dòng)時(shí)出發(fā)
*/
@Slf4j
@Configuration
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {
@Resource
GoodsMapper goodsMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("Web項(xiàng)目啟動(dòng),ApplicationListener監(jiān)聽器觸發(fā)...");
List<Goods> goodsList = goodsMapper.findGoods();
for (Goods goods : goodsList) {
redisTemplate.boundHashOps("goods_info").put(goods.getGoods_id(), goods.getGoods_stock());
log.info("緩存商品詳情:{}",goods);
}
}
}3、Redis實(shí)現(xiàn)分布式鎖
3.1 分布式鎖的實(shí)現(xiàn)類
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisException;
import java.util.List;
import java.util.UUID;
public class DistributedLock {
//redis連接池
private static JedisPool jedisPool;
static {
JedisPoolConfig config = new JedisPoolConfig();
// 設(shè)置最大連接數(shù)
config.setMaxTotal(200);
// 設(shè)置最大空閑數(shù)
config.setMaxIdle(8);
// 設(shè)置最大等待時(shí)間
config.setMaxWaitMillis(1000 * 100);
// 在borrow一個(gè)jedis實(shí)例時(shí),是否需要驗(yàn)證,若為true,則所有jedis實(shí)例均是可用的
config.setTestOnBorrow(true);
jedisPool = new JedisPool(config, "192.168.3.28", 6379, 3000);
}
/**
* 加鎖
* @param lockName 鎖的key
* @param acquireTimeout 獲取鎖的超時(shí)時(shí)間
* @param timeout 鎖的超時(shí)時(shí)間
* @return 鎖標(biāo)識(shí)
* Redis Setnx(SET if Not eXists) 命令在指定的 key 不存在時(shí),為 key 設(shè)置指定的值。
* 設(shè)置成功,返回 1 。 設(shè)置失敗,返回 0 。
*/
public String lockWithTimeout(String lockName, long acquireTimeout, long timeout) {
Jedis conn = null;
String retIdentifier = null;
try {
// 獲取連接
conn = jedisPool.getResource();
// value值->隨機(jī)生成一個(gè)String
String identifier = UUID.randomUUID().toString();
// key值->即鎖名
String lockKey = "lock:" + lockName;
// 超時(shí)時(shí)間->上鎖后超過(guò)此時(shí)間則自動(dòng)釋放鎖 毫秒轉(zhuǎn)成->秒
int lockExpire = (int) (timeout / 1000);
// 獲取鎖的超時(shí)時(shí)間->超過(guò)這個(gè)時(shí)間則放棄獲取鎖
long end = System.currentTimeMillis() + acquireTimeout;
while (System.currentTimeMillis() < end) { //在獲取鎖時(shí)間內(nèi)
if (conn.setnx(lockKey, identifier) == 1) {//設(shè)置鎖成功
conn.expire(lockKey, lockExpire);
// 返回value值,用于釋放鎖時(shí)間確認(rèn)
retIdentifier = identifier;
return retIdentifier;
}
// ttl以秒為單位返回 key 的剩余過(guò)期時(shí)間,返回-1代表key沒(méi)有設(shè)置超時(shí)時(shí)間,為key設(shè)置一個(gè)超時(shí)時(shí)間
if (conn.ttl(lockKey) == -1) {
conn.expire(lockKey, lockExpire);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
return retIdentifier;
}
/**
* 釋放鎖
* @param lockName 鎖的key
* @param identifier 釋放鎖的標(biāo)識(shí)
* @return
*/
public boolean releaseLock(String lockName, String identifier) {
Jedis conn = null;
String lockKey = "lock:" + lockName;
boolean retFlag = false;
try {
conn = jedisPool.getResource();
while (true) {
// 監(jiān)視lock,準(zhǔn)備開始redis事務(wù)
conn.watch(lockKey);
// 通過(guò)前面返回的value值判斷是不是該鎖,若是該鎖,則刪除,釋放鎖
if (identifier.equals(conn.get(lockKey))) {
Transaction transaction = conn.multi();//開啟redis事務(wù)
transaction.del(lockKey);
List<Object> results = transaction.exec();//提交redis事務(wù)
if (results == null) {//提交失敗
continue;//繼續(xù)循環(huán)
}
retFlag = true;//提交成功
}
conn.unwatch();//解除監(jiān)控
break;
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
return retFlag;
}
}3.2 分布式鎖的業(yè)務(wù)代碼
service業(yè)務(wù)邏輯層
public interface SkillService {
Integer seckill(String goodsId,Long goodsStock);
}service業(yè)務(wù)邏輯層實(shí)現(xiàn)層
import com.springlock.lock.DistributedLock;
import com.springlock.mapper.GoodsMapper;
import com.springlock.pojo.Goods;
import com.springlock.service.SkillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Slf4j
@Service
public class SkillServiceImpl implements SkillService {
private final DistributedLock lock = new DistributedLock();
private final static String LOCK_NAME = "goods_stock_resource";
@Resource
GoodsMapper goodsMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public Integer seckill(String goodsId, Long goodsQuantity) {
// 加鎖,返回鎖的value值,供釋放鎖時(shí)候進(jìn)行判斷
String identifier = lock.lockWithTimeout(LOCK_NAME, 5000, 1000);
Integer goods_stock = (Integer) redisTemplate.boundHashOps("goods_info").get(goodsId);
if (goods_stock > 0 && goods_stock >= goodsQuantity) {
//1.查詢數(shù)據(jù)庫(kù)對(duì)象
Goods goods = goodsMapper.findGoodsById(goodsId);
//2.更新數(shù)據(jù)庫(kù)中庫(kù)存數(shù)量
goods.setGoods_stock(goods.getGoods_stock() - goodsQuantity);
goodsMapper.updateGoodsStock(goods);
//3.同步Redis中商品庫(kù)存
redisTemplate.boundHashOps("goods_info").put(goods.getGoods_id(), goods.getGoods_stock());
log.info("商品Id:{},在Redis中剩余庫(kù)存數(shù)量:{}", goodsId, goods.getGoods_stock());
//釋放鎖
lock.releaseLock(LOCK_NAME, identifier);
return 1;
} else {
log.info("商品Id:{},庫(kù)存不足!,庫(kù)存數(shù):{},購(gòu)買量:{}", goodsId, goods_stock, goodsQuantity);
//釋放鎖
lock.releaseLock(LOCK_NAME, identifier);
return -1;
}
}
}controller層
import com.springlock.service.SkillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Scope("prototype") //prototype 多實(shí)例,singleton單實(shí)例
public class SkillController {
@Autowired
SkillService skillService;
@RequestMapping("/skill")
public String skill() {
Integer count = skillService.seckill("1", 1L);
return count > 0 ? "下單成功" + count : "下單失敗" + count;
}
}4、分布式鎖測(cè)試
把SpringBoot工程啟動(dòng)兩臺(tái)服務(wù)器,端口分別為8888、9999。啟動(dòng)8888端口后,修改配置文件端口為9999,啟動(dòng)另一個(gè)應(yīng)用

然后使用jmeter進(jìn)行并發(fā)測(cè)試,開兩個(gè)線程組,分別代表兩臺(tái)服務(wù)器下單,1秒鐘起20個(gè)線程,循環(huán)25次,總共下單1000次。

查看控制臺(tái)輸出:

注意:該鎖在并發(fā)量太高的情況下,會(huì)出現(xiàn)一部分失敗率。手動(dòng)寫的程序,因?yàn)椴僮鞯姆窃有?,?huì)存在并發(fā)問(wèn)題。該鎖的實(shí)現(xiàn)只是為了演示原理,并不適用于生產(chǎn)。

jmeter聚合報(bào)告

總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Spring Boot自定義favicon實(shí)現(xiàn)方法實(shí)例解析
這篇文章主要介紹了Spring Boot自定義favicon實(shí)現(xiàn)方法實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Java線程中synchronized和volatile關(guān)鍵字的區(qū)別詳解
這篇文章主要介紹了Java線程中synchronized和volatile關(guān)鍵字的區(qū)別詳解,synchronzied既能夠保障可見(jiàn)性,又能保證原子性,而volatile只能保證可見(jiàn)性,無(wú)法保證原子性,volatile不需要加鎖,比synchronized更輕量級(jí),不會(huì)阻塞線程,需要的朋友可以參考下2024-01-01
詳解用maven搭建springboot環(huán)境的方法
本篇文章主要介紹了詳解用maven搭建springboot環(huán)境的方法,這里整理了詳細(xì)的代碼,非常具有實(shí)用價(jià)值,有需要的小伙伴可以參考下2017-08-08
springboot+mybatis+redis 二級(jí)緩存問(wèn)題實(shí)例詳解
Mybatis默認(rèn)沒(méi)有開啟二級(jí)緩存,需要在全局配置(mybatis-config.xml)中開啟二級(jí)緩存。本文講述的是使用Redis作為緩存,與springboot、mybatis進(jìn)行集成的方法。需要的朋友參考下吧2017-12-12
SpringBoot+MyBatisPlus+MySQL8實(shí)現(xiàn)樹形結(jié)構(gòu)查詢
這篇文章主要為大家詳細(xì)介紹了SpringBoot+MyBatisPlus+MySQL8實(shí)現(xiàn)樹形結(jié)構(gòu)查詢,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
J2EE Servlet上傳文件到服務(wù)器并相應(yīng)顯示功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了J2EE Servlet上傳文件到服務(wù)器,并相應(yīng)顯示,在文中上傳方式使用的是post不能使用get,具體實(shí)例代碼大家參考下本文2018-07-07
JavaCV實(shí)戰(zhàn)之調(diào)用攝像頭基礎(chǔ)詳解
這篇文章主要介紹了使用JavaCV框架對(duì)攝像頭進(jìn)行各種處理的基礎(chǔ)理論詳解,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)JavaCV有一定的幫助,需要的可以了解一下2022-01-01

