您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“redis實現分布式鎖實例分析”,內容詳細,步驟清晰,細節處理妥當,希望這篇“redis實現分布式鎖實例分析”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
模擬一個電商系統,服務器分布式部署,系統中有一個用戶下訂單的接口,用戶下訂單之前需要獲取分布式鎖,然后去檢查一下庫存,確保庫存足夠了才會給用戶下單,然后釋放鎖。
由于系統有一定的并發,所以會預先將商品的庫存保存在redis中,用戶下單的時候會更新redis的庫存。
-- ---------------------------- -- 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');
<?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> <!--導入SpringBoot的父工程 把系統中的版本號做了一些定義! --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <dependencies> <!--導入SpringBoot的Web場景啟動器 Web相關的包導入!--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--導入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> <!--導入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>
# SpringBoot有默認的配置,我們可以覆蓋默認的配置 server.port=8888 # 配置數據的連接信息 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
/** * @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); } }
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.創建JedisPoolConfig對象。在該對象中完成一些鏈接池配置 * @ConfigurationProperties:會將前綴相同的內容創建一個實體。 */ @Bean @ConfigurationProperties(prefix="spring.redis.jedis.pool") public JedisPoolConfig jedisPoolConfig(){ JedisPoolConfig config = new JedisPoolConfig(); log.info("JedisPool默認參數-最大空閑數:{},最小空閑數:{},最大鏈接數:{}",config.getMaxIdle(),config.getMinIdle(),config.getMaxTotal()); return config; } /** * 2.創建JedisConnectionFactory:配置redis鏈接信息 */ @Bean @ConfigurationProperties(prefix="spring.redis") public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){ log.info("redis初始化配置-最大空閑數:{},最小空閑數:{},最大鏈接數:{}",config.getMaxIdle(),config.getMinIdle(),config.getMaxTotal()); JedisConnectionFactory factory = new JedisConnectionFactory(); //關聯鏈接池的配置對象 factory.setPoolConfig(config); return factory; } /** * 3.創建RedisTemplate:用于執行Redis操作的方法 */ @Bean public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){ RedisTemplate<String, Object> template = new RedisTemplate<>(); //關聯 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); //設置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); return template; } }
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; }
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-根據ID查詢 * @param goodsId * @return */ @Select("select * from t_goods where goods_id=#{goods_id}") Goods findGoodsById(String goodsId); }
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監聽器,項目啟動時出發 */ @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監聽器觸發..."); List<Goods> goodsList = goodsMapper.findGoods(); for (Goods goods : goodsList) { redisTemplate.boundHashOps("goods_info").put(goods.getGoods_id(), goods.getGoods_stock()); log.info("緩存商品詳情:{}",goods); } } }
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(); // 設置最大連接數 config.setMaxTotal(200); // 設置最大空閑數 config.setMaxIdle(8); // 設置最大等待時間 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 設置指定的值。 * 設置成功,返回 1 。 設置失敗,返回 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; // 超時時間->上鎖后超過此時間則自動釋放鎖 毫秒轉成->秒 int lockExpire = (int) (timeout / 1000); // 獲取鎖的超時時間->超過這個時間則放棄獲取鎖 long end = System.currentTimeMillis() + acquireTimeout; while (System.currentTimeMillis() < end) { //在獲取鎖時間內 if (conn.setnx(lockKey, identifier) == 1) {//設置鎖成功 conn.expire(lockKey, lockExpire); // 返回value值,用于釋放鎖時間確認 retIdentifier = identifier; return retIdentifier; } // ttl以秒為單位返回 key 的剩余過期時間,返回-1代表key沒有設置超時時間,為key設置一個超時時間 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) { // 監視lock,準備開始redis事務 conn.watch(lockKey); // 通過前面返回的value值判斷是不是該鎖,若是該鎖,則刪除,釋放鎖 if (identifier.equals(conn.get(lockKey))) { Transaction transaction = conn.multi();//開啟redis事務 transaction.del(lockKey); List<Object> results = transaction.exec();//提交redis事務 if (results == null) {//提交失敗 continue;//繼續循環 } retFlag = true;//提交成功 } conn.unwatch();//解除監控 break; } } catch (JedisException e) { e.printStackTrace(); } finally { if (conn != null) { conn.close(); } } return retFlag; } }
service業務邏輯層
public interface SkillService { Integer seckill(String goodsId,Long goodsStock); }
service業務邏輯層實現層
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.查詢數據庫對象 Goods goods = goodsMapper.findGoodsById(goodsId); //2.更新數據庫中庫存數量 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中剩余庫存數量:{}", goodsId, goods.getGoods_stock()); //釋放鎖 lock.releaseLock(LOCK_NAME, identifier); return 1; } else { log.info("商品Id:{},庫存不足!,庫存數:{},購買量:{}", 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; } }
把SpringBoot工程啟動兩臺服務器,端口分別為8888、9999。啟動8888端口后,修改配置文件端口為9999,啟動另一個應用
然后使用jmeter進行并發測試,開兩個線程組,分別代表兩臺服務器下單,1秒鐘起20個線程,循環25次,總共下單1000次。
查看控制臺輸出:
注意:該鎖在并發量太高的情況下,會出現一部分失敗率。手動寫的程序,因為操作的非原子性,會存在并發問題。該鎖的實現只是為了演示原理,并不適用于生產。
jmeter聚合報告
讀到這里,這篇“redis實現分布式鎖實例分析”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。