redis實現(xiàn)分布式鎖實例詳解
1、業(yè)務(wù)場景引入
模擬一個電商系統(tǒng),服務(wù)器分布式部署,系統(tǒng)中有一個用戶下訂單的接口,用戶下訂單之前需要獲取分布式鎖,然后去檢查一下庫存,確保庫存足夠了才會給用戶下單,然后釋放鎖。
由于系統(tǒng)有一定的并發(fā),所以會預(yù)先將商品的庫存保存在redis中,用戶下單的時候會更新redis的庫存。
2、基礎(chǔ)環(huán)境準備
2.1.準備庫存數(shù)據(jù)庫
-- ----------------------------
-- 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)入依賴,請注意版本。
<?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)中的版本號做了一些定義! -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<!--導(dǎo)入SpringBoot的Web場景啟動器 Web相關(guān)的包導(dǎo)入!-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--導(dǎo)入MyBatis的場景啟動器-->
<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單元測試-->
<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 的啟動器 -->
<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>
<!--編譯的時候同時也把包下面的xml同時編譯進去-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>2.3.application.properties配置文件
# SpringBoot有默認的配置,我們可以覆蓋默認的配置 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啟動類
/**
* @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對象。在該對象中完成一些鏈接池配置
* @ConfigurationProperties:會將前綴相同的內(nèi)容創(chuàng)建一個實體。
*/
@Bean
@ConfigurationProperties(prefix="spring.redis.jedis.pool")
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig config = new JedisPoolConfig();
log.info("JedisPool默認參數(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)鏈接池的配置對象
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來序列化和反序列化redis的value值(默認使用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等會跑出異常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
//使用StringRedisSerializer來序列化和反序列化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-更新商品庫存
* @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啟動事件,加載商品數(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)聽器,項目啟動時出發(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項目啟動,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實現(xiàn)分布式鎖
3.1 分布式鎖的實現(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è)置最大等待時間
config.setMaxWaitMillis(1000 * 100);
// 在borrow一個jedis實例時,是否需要驗證,若為true,則所有jedis實例均是可用的
config.setTestOnBorrow(true);
jedisPool = new JedisPool(config, "192.168.3.28", 6379, 3000);
}
/**
* 加鎖
* @param lockName 鎖的key
* @param acquireTimeout 獲取鎖的超時時間
* @param timeout 鎖的超時時間
* @return 鎖標識
* Redis Setnx(SET if Not eXists) 命令在指定的 key 不存在時,為 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值->隨機生成一個String
String identifier = UUID.randomUUID().toString();
// key值->即鎖名
String lockKey = "lock:" + lockName;
// 超時時間->上鎖后超過此時間則自動釋放鎖 毫秒轉(zhuǎn)成->秒
int lockExpire = (int) (timeout / 1000);
// 獲取鎖的超時時間->超過這個時間則放棄獲取鎖
long end = System.currentTimeMillis() + acquireTimeout;
while (System.currentTimeMillis() < end) { //在獲取鎖時間內(nèi)
if (conn.setnx(lockKey, identifier) == 1) {//設(shè)置鎖成功
conn.expire(lockKey, lockExpire);
// 返回value值,用于釋放鎖時間確認
retIdentifier = identifier;
return retIdentifier;
}
// ttl以秒為單位返回 key 的剩余過期時間,返回-1代表key沒有設(shè)置超時時間,為key設(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 釋放鎖的標識
* @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,準備開始redis事務(wù)
conn.watch(lockKey);
// 通過前面返回的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ù)邏輯層實現(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值,供釋放鎖時候進行判斷
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ù)庫對象
Goods goods = goodsMapper.findGoodsById(goodsId);
//2.更新數(shù)據(jù)庫中庫存數(shù)量
goods.setGoods_stock(goods.getGoods_stock() - goodsQuantity);
goodsMapper.updateGoodsStock(goods);
//3.同步Redis中商品庫存
redisTemplate.boundHashOps("goods_info").put(goods.getGoods_id(), goods.getGoods_stock());
log.info("商品Id:{},在Redis中剩余庫存數(shù)量:{}", goodsId, goods.getGoods_stock());
//釋放鎖
lock.releaseLock(LOCK_NAME, identifier);
return 1;
} else {
log.info("商品Id:{},庫存不足!,庫存數(shù):{},購買量:{}", 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 多實例,singleton單實例
public class SkillController {
@Autowired
SkillService skillService;
@RequestMapping("/skill")
public String skill() {
Integer count = skillService.seckill("1", 1L);
return count > 0 ? "下單成功" + count : "下單失敗" + count;
}
}4、分布式鎖測試
把SpringBoot工程啟動兩臺服務(wù)器,端口分別為8888、9999。啟動8888端口后,修改配置文件端口為9999,啟動另一個應(yīng)用

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

查看控制臺輸出:

注意:該鎖在并發(fā)量太高的情況下,會出現(xiàn)一部分失敗率。手動寫的程序,因為操作的非原子性,會存在并發(fā)問題。該鎖的實現(xiàn)只是為了演示原理,并不適用于生產(chǎn)。

jmeter聚合報告

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

