加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Redisson基本用法

发布时间:2020-12-15 06:51:52 所属栏目:Java 来源:网络整理
导读:1.? Redisson Redisson是Redis官方推荐的Java版的Redis客户端。它提供的功能非常多,也非常强大,此处我们只用它的分布式锁功能。 https://github.com/redisson/redisson 1.1.? 基本用法 1 dependency 2 groupId org.redisson /groupId 3 artifactId redisso

1.? Redisson

Redisson是Redis官方推荐的Java版的Redis客户端。它提供的功能非常多,也非常强大,此处我们只用它的分布式锁功能。

https://github.com/redisson/redisson

1.1.? 基本用法

1 <dependency>
2    <groupId>org.redisson</groupId>
3    <artifactId>redisson</artifactId>
4    <version>3.11.1</version>
5 </dependency>

1.2.? Distributed locks and synchronizers

RedissonClient中提供了好多种锁,还有其它很多实用的方法

1.2.1.? Lock

默认,非公平锁

最简洁的一种方法

指定超时时间?

异步

1.2.2? Fair Lock?

1.2.3??MultiLock

1.2.4??RedLock

1.3.? 示例

pom.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <parent>
 6         <groupId>org.springframework.boot 7         <artifactId>spring-boot-starter-parent 8         <version>2.1.6.RELEASE 9         <relativePath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupId>com.cjs.example12     <artifactId>cjs-redisson-example13     <version>0.0.1-SNAPSHOT14     <name>cjs-redisson-example</name>
15 
16     <properties>
17         <java.version>1.8</java.version>
18     </properties>
19 
20     <dependencies>
21         22             23             <artifactId>spring-boot-starter-data-jpa24         </dependency>
25         26             27             <artifactId>spring-boot-starter-data-redis28         29         30             31             <artifactId>spring-boot-starter-web32         33 
34         <!-- https://github.com/redisson/redisson#quick-start -->
35         36             37             38             39         40 
41 
42         43             <groupId>org.apache.commons44             <artifactId>commons-lang345             <version>3.946         47         48             <groupId>com.alibaba49             <artifactId>fastjson50             <version>1.2.5851         52         53             54             <artifactId>commons-pool255             <version>2.6.256         57 
58         59             <groupId>mysql60             <artifactId>mysql-connector-java61             <scope>runtime</scope>
62         63         64             <groupId>org.projectlombok65             <artifactId>lombok66             <optional>true</optional>
67         68     </dependencies>
69 
70     <build>
71         <plugins>
72             <plugin>
73                 74                 <artifactId>spring-boot-maven-plugin75             </plugin>
76         </plugins>
77     </build>
78 
79 </project>

application.yml

 1 server:
 2   port: 8080
 3 spring 4   application 5     namecjs-redisson-example
 6   redis 7     cluster 8       nodes10.0.29.30:6379, 29.9529.2056379
 9     lettuce10       pool11         min-idle0
12         max8
13         active20
14   datasource15     urljdbc:mysql://127.0.0.1:3306/test
16     usernameroot
17     password123456
18     driverclasscom.mysql.cj.jdbc.Driver
19     typecom.zaxxer.hikari.HikariDataSource

RedissonConfig.java

 1 package com.cjsexamplelockconfig;
 2 
 3 import org.redisson.Redisson 4 org.redisson.api.RedissonClient 5 org.redisson.config.Config 6 org.springframework.context.annotation.Bean 7 org.springframework.context.annotation.Configuration 8 
 9 /**
10  * @author ChengJianSheng
11  * @date 2019-07-26
12  */
13 @Configuration
14 public class RedissonConfig {
15 
16     @Bean
17     public RedissonClient redissonClient() 18         Config config = new Config();
19         useClusterServers()
20                 setScanInterval(2000)
21                 addNodeAddress("redis://10.0.29.30:6379""redis://10.0.29.95:6379"22                 "redis://10.0.29.205:6379");
23 
24         RedissonClient redisson = Redissoncreate(25 
26         return redisson27     }
28 
29 }

CourseServiceImpl.java?

1 serviceimpl 2 3 com.alibaba.fastjson.JSON 4 com.cjs.example.lock.constant.RedisKeyPrefixConstant 5 com.cjs.example.lock.model.CourseModel 6 com.cjs.example.lock.model.CourseRecordModel 7 com.cjs.example.lock.repository.CourseRecordRepository 8 com.cjs.example.lock.repository.CourseRepository 9 com.cjs.example.lock.service.CourseService 10 lombok.extern.slf4j.Slf4j 11 org.apache.commons.lang3.StringUtils 12 org.redisson.api.RLock 13 14 org.springframework.beans.factory.annotation.Autowired 15 org.springframework.data.redis.core.HashOperations 16 org.springframework.data.redis.core.StringRedisTemplate 17 org.springframework.stereotype.Service 18 19 java.util.concurrent.TimeUnit 20 21 22 23 24 25 @Slf4j 26 @Service 27 CourseServiceImpl implements CourseService 28 29 @Autowired 30 private CourseRepository courseRepository 31 32 CourseRecordRepository courseRecordRepository 33 34 StringRedisTemplate stringRedisTemplate 35 36 37 38 @Override 39 CourseModel getByIdInteger courseId) 40 41 CourseModel courseModel null 42 43 HashOperations<String> hashOperations opsForHash 44 45 String value hashOperationsgetRedisKeyPrefixConstantCOURSEvalueOf)); 46 47 if StringUtilsisBlankvalue)) 48 lockKey LOCK_COURSE + 49 RLock lock getLocklockKey 50 try 51 boolean res tryLock10TimeUnitSECONDS 52 res 53 54 55 loginfo"从数据库中读取" 56 findById).orElse( 57 put),1)">JSONtoJSONStringcourseModel 58 59 60 } catch InterruptedException e 61 printStackTrace 62 finally 63 unlock 64 65 else 66 "从缓存中读取" 67 parSEObjectCourseModelclass 68 69 70 71 72 73 74 void uploaduserIdstudyProcess 75 76 77 78 cacheKey COURSE_PROGRESS + ":" 79 cacheValue cacheKey 80 isNotBlankcacheValue&& studyProcess <= Integer 81 return 82 83 84 = "upload:" userId 85 86 87 88 89 90 91 92 || 93 CourseRecordModel model CourseRecordModel 94 modelsetUserId 95 setCourseId 96 setStudyProcess 97 save 98 99 100 101 Exception ex102 error"获取所超时!"103 104 105 106 107 108 }

StockServiceImpl.java

com.cjs.example.lock.service.StockService 8 9 10 13 14 15 16 StockServiceImpl StockService 17 18 19 20 21 22 int getByProductproductId23 STOCK25 26 return 027 28 29 30 31 32 boolean decrease33 int stock 34 <= 35 return false36 37 38 - 139 true40 41 }

OrderServiceImpl.java

com.cjs.example.lock.model.OrderModelcom.cjs.example.lock.repository.OrderRepositorycom.cjs.example.lock.service.OrderService10 11 12 13 java.util.Date14 java.util.UUID15 16 17 18 19 * @date 2019-07-30 20 21 22 23 OrderServiceImpl OrderService 24 25 26 StockService stockService27 28 OrderRepository orderRepository29 30 31 32 33 * 乐观锁 34 */ 35 36 String 37 "剩余库存:{}"stock40 41 42 43 // 如果不加锁,必然超卖 44 45 "stock:" 46 47 48 49 50 orderNo UUIDrandomUUID().toStringreplace"-"""toUpperCase51 52 53 54 OrderModel orderModel OrderModel55 orderModel56 setProductId57 setOrderNoorderNo58 Date now Date59 setCreateTimenow60 setUpdateTime61 62 63 64 65 66 67 "下单失败"68 69 70 71 72 73 74 75 }

OrderModel.java

lombok.Data 4 javax.persistence.*java.io.Serializable@Data 14 @Entity @Tablename "t_order"OrderModel Serializable @Id 19 @GeneratedValuestrategy GenerationTypeIDENTITY20 id21 22 @Column"order_no"23 "product_id"27 28 "user_id"29 "create_time"createTime33 34 "update_time"35 updateTime36 }?

数据库脚本.sql

1 SET NAMES utf8mb4; 2 SET FOREIGN_KEY_CHECKS = 0 3 4 -- ---------------------------- 5 -- Table structure for t_course 6 7 DROP TABLE IF EXISTS `t_course 8 CREATE TABLE ` ( 9 int(11) NOT NULL AUTO_INCREMENT, 10 course_namevarchar(64NULL11 course_typetinyint(4NULL DEFAULT '1'12 start_timedatetime 13 PRIMARY KEY (14 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET16 -- Table structure for t_order 19 t_order20 21 22 order_no256CHARACTER latin1 23 user_id24 product_id25 create_time26 update_timeDEFAULT ON UPDATE CURRENT_TIMESTAMP27 28 109 utf8mb4 COLLATEutf8mb4_bin; 29 30 31 -- Table structure for t_user_course_record 32 33 t_user_course_record34 35 36 37 course_id38 study_process39 40 103 41 42 1;?

1.4? 工程结构

https://github.com/chengjiansheng/cjs-redisson-example?

1.5? Redis集群创建

1.6? 测试

测试/course/upload

测试/order/create

2.? Spring Integration

用法与Redisson类似

2 3 <artifactId>spring-boot-starter-integration4 6 <groupId>org.springframework.integration7 <artifactId>spring-integration-redis8 </dependency>
kaishustorybaseconforg.springframework.data.redis.connection.RedisConnectionFactoryorg.springframework.integration.redis.util.RedisLockRegistry 7 8 12 13 RedisLockConfig 14 15 16 RedisLockRegistry redisLockRegistryRedisConnectionFactory redisConnectionFactory17 new RedisLockRegistry"asdf"18 19 20 }
1 RedisLockRegistry 4 5 6 "order:" 8 Lock obtain 9 10 11 12 //todo 13 14 15 16 18 }

3.? 其它

https://github.com/redisson/redisson/wiki/8.-Distributed-locks-and-synchronizers?

https://www.cnblogs.com/cjsblog/p/9831423.html?

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读