大家好 , 我是苏麟 , 今天带来 Redisson 使用 .
官方文档 : GitHub - redisson/redisson: Redisson - Easy Redis Java client with features of In-Memory Data Grid. Sync/Async/RxJava/Reactive API. Over 50 Redis based Java objects and services: Set, Multimap, SortedSet, Map, List, Queue, Deque, Semaphore, Lock, AtomicLong, Map Reduce, Bloom filter, Spring Cache, Tomcat, Scheduler, JCache API, Hibernate, RPC, local cache ...
引入依赖
<!--https://github.com/redisson/redisson#quick-start--><dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.23.2</version></dependency>
yml配置(例如)
#redis 配置redis:port: 6379database: 1host: localhost
Redisson配置
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class RedissonConfig {private String host;private String port;@Beanpublic RedissonClient redissonClient(){// 1.创建配置Config config = new Config();String redissonAddress = String.format("redis:/%s:%s",host,port);//useClusterServers()集群//setDatabase() 设置那个redis库config.useSingleServer().setAddress(redissonAddress).setDatabase(2);//2.创建实例RedissonClient redissonClient = Redisson.create(config);return redissonClient;}
}
这里@ConfigurationProperties(prefix = "spring.redis")用法请看 : 读取/加载 properties/yml 配置文件_踏遍三十六岸的博客-CSDN博客
像操作本地集合一样操作Redisson
@SpringBootTest
class UserCenterApplicationTests {@Resourceprivate RedissonClient redissonClient;@Testvoid test() {//list操作 数据存在 JVM 内存中List<String> list = new ArrayList<>();list.add("sl");System.out.println(list.get(0));list.remove(0);//数据存在 Redis 内存中//getList()取列表名字 因为 redis 中是 key-value 存在RList<String> rList = redissonClient.getList("redisson-list");rList.add("sl-redisson");System.out.println(rList.get(0));rList.remove(0); }@Testvoid hashTest(){//哈希操作RMap<String, String> rMap = redissonClient.getMap("LiJiaWei");//设置 map 中的 key - valuerMap.put("sl","1");rMap.put("jw","2");System.out.println(redissonClient.getMap("LiJiaWei").get("sl"));System.out.println(redissonClient.getMap("LiJiaWei").get("jw"));redissonClient.getMap("LiJiaWei").remove("sl");redissonClient.getMap("LiJiaWei").remove("jw");}//......//其他操作都一样
}
Redssion 分布式锁
@Component
public class PreScheduled {@Resourceprivate RedissonClient redissonClient;/*** 每天执行*/@Scheduled(cron = "0 59 23 * * *")public void doCah() {//获取锁 , 可重入 指定锁的名称RLock lock = redissonClient.getLock("sl:redisson:cache:lock");try {/*** 只有一个线程获取到锁* 等待时间 , 执行时间 , 毫秒*/if (lock.tryLock(0, 30000L, TimeUnit.MILLISECONDS)) {//...}} catch (InterruptedException e) {e.printStackTrace();} finally {/*** 只能释放自己加的锁*/if (lock.isHeldByCurrentThread()) {lock.unlock();}}}
}
感兴趣的小伙伴可以自行了解下面知识!
Redisson的可重入锁原理
Redisson看门狗WatchDog机制
Redisson的multiLock原理
这期就到这里 , 拜拜 !