Redis分布式客户端之Redisson的基本使用

转载:https://blog.csdn.net/u010963948/article/details/79240050

这里先简单介绍下我的项目里面的基本使用,redis服务采用的是三主三从模式。

1、配置文件代码如下:

[java]  view plain  copy
  1. package com.whb.redisson.demoOne.properties;  
  2.   
  3. import org.redisson.config.ClusterServersConfig;  
  4. import org.springframework.boot.context.properties.ConfigurationProperties;  
  5. import org.springframework.context.annotation.Configuration;  
  6.   
  7. /** 
  8.  * @author whb 
  9.  * @date 2018年2月2日 下午3:14:54  
  10.  * @Description: redis的集群配置(还有其他主从配置BaseMasterSlaveServersConfig等) 
  11.  */  
  12. @Configuration  
  13. @ConfigurationProperties(prefix = "dislock.redisson.clusterServersConfig")  
  14. public class ClusterServerConfigProperties extends ClusterServersConfig {  
  15. }  
2、初始化文件如下:

[java]  view plain  copy
  1. package com.whb.redisson.demoOne;  
  2.   
  3. import java.net.URI;  
  4. import java.util.List;  
  5.   
  6. import org.redisson.Redisson;  
  7. import org.redisson.api.RedissonClient;  
  8. import org.redisson.config.ClusterServersConfig;  
  9. import org.redisson.config.Config;  
  10. import org.springframework.beans.BeanUtils;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;  
  13. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
  14. import org.springframework.boot.context.properties.EnableConfigurationProperties;  
  15. import org.springframework.context.annotation.Bean;  
  16. import org.springframework.context.annotation.Configuration;  
  17. import org.springframework.context.annotation.Primary;  
  18.   
  19. import com.whb.redisson.demoOne.properties.ClusterServerConfigProperties;  
  20.   
  21. /** 
  22.  * @author whb 
  23.  * @date 2018年2月2日 下午3:16:25  
  24.  * @Description: 分布式锁,解决资源竞争问题 
  25.  */  
  26. @Configuration  
  27. @ConditionalOnClass(Config.class)  
  28. @EnableConfigurationProperties(ClusterServerConfigProperties.class)  
  29. public class EnableRedissonAutoConfiguration {  
  30.   
  31.     /** 集群的配置 */  
  32.     @Autowired  
  33.     private ClusterServerConfigProperties clusterServerConfigProperties;  
  34.   
  35.   
  36.     /** 
  37.      * 集群模式自动装配 
  38.      * @return 
  39.      */  
  40.     @Bean  
  41.     @Primary  
  42.     //@ConditionalOnExpression("'${dislock.redisson.clusterServersConfig.idleConnectionTimeout}'=='10000'")  
  43.     @ConditionalOnProperty(prefix = "dislock.redisson",name = "startup",matchIfMissing = false)  
  44.     public RedissonClient redissonCluster() {  
  45.         Config config = new Config();  
  46.         ClusterServersConfig serverConfig = config.useClusterServers();  
  47.         BeanUtils.copyProperties(clusterServerConfigProperties,serverConfig);  
  48.         List<URI> nodeAddresses = clusterServerConfigProperties.getNodeAddresses();  
  49.   
  50.         int size = nodeAddresses.size();  
  51.         String[] address = new String[size];  
  52.         for(int i=0;i<size;i++){  
  53.             address[i] = nodeAddresses.get(i).toString();  
  54.         }  
  55.   
  56.         serverConfig.addNodeAddress(address);  
  57.   
  58.         return Redisson.create(config);  
  59.     }  
  60. }  

3、使用教程如下:

[java]  view plain  copy
  1. @Autowired  
  2.     RedissonClient redissonClient;  
  3.       
  4.     public void getLock(){  
  5.         RLock lock = redissonClient.getLock("123");  
  6.         try{  
  7.             boolean b = lock.tryLock(520, TimeUnit.SECONDS);  
  8.             if(!b){  
  9.                 throw new RuntimeException("-------------");  
  10.             }  
  11.             Thread.sleep(500L);  
  12.         } catch (InterruptedException e) {  
  13.             e.printStackTrace();  
  14.         } finally {  
  15.             lock.unlock();  
  16.         }  
  17.     }  

4、Redission的基本使用如下:

简介

Redisson - 是一个高级的分布式协调Redis客服端,能帮助用户在分布式环境中轻松实现一些Java的对象 (Bloom filter, BitSet, Set, SetMultimap, ScoredSortedSet, SortedSet, Map, ConcurrentMap, List, ListMultimap, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, ReadWriteLock, AtomicLong, CountDownLatch, Publish / Subscribe, HyperLogLog)。

支持Redis多种连接模式

集群模式



Config config = new Config();
config.useClusterServers()
    .setScanInterval(2000) // cluster state scan interval in milliseconds
    .addNodeAddress("127.0.0.1:7000", "127.0.0.1:7001")
    .addNodeAddress("127.0.0.1:7002");
RedissonClient redisson = Redisson.create(config);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

单例模式



// connects to 127.0.0.1:6379 by default
RedissonClient redisson = Redisson.create();
Config config = new Config();
config.useSingleServer().setAddress("myredisserver:6379");
RedissonClient redisson = Redisson.create(config);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

哨兵模式


Config config = new Config();
config.useSentinelServers()
    .setMasterName("mymaster")
    .addSentinelAddress("127.0.0.1:26389", "127.0.0.1:26379")
    .addSentinelAddress("127.0.0.1:26319");
RedissonClient redisson = Redisson.create(config);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

主从模式


Config config = new Config();
config.useMasterSlaveServers()
    .setMasterAddress("127.0.0.1:6379")
    .addSlaveAddress("127.0.0.1:6389", "127.0.0.1:6332", "127.0.0.1:6419")
    .addSlaveAddress("127.0.0.1:6399");
RedissonClient redisson = Redisson.create(config);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

操作执行

Redisson支持自动重试策略,默认是重试3次,间隔为1000ms。除了支持同步操作外,还支持异步方式和响应方式。


RedissonClient client = Redisson.create(config);
RAtomicLong longObject = client.getAtomicLong('myLong');
// sync way
longObject.compareAndSet(3, 401);
// async way
longObject.compareAndSetAsync(3, 401);
RedissonReactiveClient client = Redisson.createReactive(config);
RAtomicLongReactive longObject = client.getAtomicLong('myLong');
// reactive way
longObject.compareAndSet(3, 401);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

多种序列号方式

Codec class name Description 
org.redisson.codec.JsonJacksonCodec Jackson JSON codec. Default codec 
org.redisson.codec.CborJacksonCodec CBOR binary json codec 
org.redisson.codec.MsgPackJacksonCodec MsgPack binary json codec 
org.redisson.codec.KryoCodec Kryo binary codec 
org.redisson.codec.SerializationCodec JDK Serialization codec 
org.redisson.codec.FstCodec FST up to 10 times faster and 100% JDK Serialization compatible codec 
org.redisson.codec.LZ4Codec LZ4 compression codec 
org.redisson.codec.SnappyCodec Snappy compression codec 
org.redisson.client.codec.StringCodec String codec 
org.redisson.client.codec.LongCodec Long codec

分布式对象

分布式Object



RBucket<AnyObject> bucket = redisson.getBucket("anyObject");
bucket.set(new AnyObject(1));
AnyObject obj = bucket.get();
bucket.trySet(new AnyObject(3));
bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
bucket.getAndSet(new AnyObject(6));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

分布式BitSet


RBitSet set = redisson.getBitSet("simpleBitset");
set.set(0, true);
set.set(1812, false);
set.clear(0);
set.addAsync("e");
set.xor("anotherBitset");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

分布式Lock


Redisson redisson = Redisson.create();
RLock lock = redisson.getLock("anyLock");
// Most familiar locking method
lock.lock();
// Lock time-to-live support
// releases lock automatically after 10 seconds
// if unlock method not invoked
lock.lock(10, TimeUnit.SECONDS);
// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
...
lock.unlock();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

分布式MultiLock


RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

分布式ReadWriteLock



RReadWriteLock rwlock = redisson.getLock("anyRWLock");
// Most familiar locking method
rwlock.readLock().lock();
// or
rwlock.writeLock().lock();
// Lock time-to-live support
// releases lock automatically after 10 seconds
// if unlock method not invoked
rwlock.readLock().lock(10, TimeUnit.SECONDS);
// or
rwlock.writeLock().lock(10, TimeUnit.SECONDS);
// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = rwlock.readLock().tryLock(100, 10, TimeUnit.SECONDS);
// or
boolean res = rwlock.writeLock().tryLock(100, 10, TimeUnit.SECONDS);
...
lock.unlock();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

分布式Semaphore


RSemaphore semaphore = redisson.getSemaphore("semaphore");
semaphore.acquire();
semaphore.acquire(23);
semaphore.tryAcquire();
semaphore.tryAcquire(23, TimeUnit.SECONDS);
semaphore.release(10);
semaphore.release();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

分布式AtomicLong


RAtomicLong atomicLong = redisson.getAtomicLong("myAtomicLong");
atomicLong.set(3);
atomicLong.incrementAndGet();
atomicLong.get();
  • 1
  • 2
  • 3
  • 4
  • 5

分布式AtomicDouble


RAtomicDouble atomicDouble = redisson.getAtomicDouble("myAtomicDouble");
atomicDouble.set(2.81);
atomicDouble.addAndGet(4.11);
atomicDouble.get();
  • 1
  • 2
  • 3
  • 4
  • 5

分布式CountDownLatch


RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch");
latch.trySetCount(1);
latch.await();
// in other thread or other JVM
RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch");
latch.countDown();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Topic


RTopic<SomeObject> topic = redisson.getTopic("anyTopic");
topic.addListener(new MessageListener<SomeObject>() {
    @Override
    public void onMessage(String channel, SomeObject message) {
        //...
    }
});
// in other thread or JVM
RTopic<SomeObject> topic = redisson.getTopic("anyTopic");
long clientsReceivedMessage = topic.publish(new SomeObject());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Topic patttern


// subscribe to all topics by `topic1.*` pattern
RPatternTopic<Message> topic1 = redisson.getPatternTopic("topic1.*");
int listenerId = topic1.addListener(new PatternMessageListener<Message>() {
    @Override
    public void onMessage(String pattern, String channel, Message msg) {
         Assert.fail();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

分布式集合

分布式Map

除此之外,还支持Multimap,这里不列出


RMap<String, SomeObject> map = redisson.getMap("anyMap");
SomeObject prevObject = map.put("123", new SomeObject());
SomeObject currentObject = map.putIfAbsent("323", new SomeObject());
SomeObject obj = map.remove("123");
map.fastPut("321", new SomeObject());
map.fastRemove("321");
Future<SomeObject> putAsyncFuture = map.putAsync("321");
Future<Void> fastPutAsyncFuture = map.fastPutAsync("321");
map.fastPutAsync("321", new SomeObject());
map.fastRemoveAsync("321");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Map eviction

现在Redis没有过期清空Map中的某个entry的功能,只能是清空Map所有的entry。Redission提供了这种功能。


RMapCache<String, SomeObject> map = redisson.getMapCache("anyMap");
// ttl = 10 minutes, 
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES);
// ttl = 10 minutes, maxIdleTime = 10 seconds
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);
// ttl = 3 seconds
map.putIfAbsent("key2", new SomeObject(), 3, TimeUnit.SECONDS);
// ttl = 40 seconds, maxIdleTime = 10 seconds
map.putIfAbsent("key2", new SomeObject(), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

分布式Set


RSet<SomeObject> set = redisson.getSet("anySet");
set.add(new SomeObject());
set.remove(new SomeObject());
  • 1
  • 2
  • 3
  • 4

除此之外还有,还支持Set eviction, SortedSet, ScoredSortedSet, LexSortedSet

分布式List


RList<SomeObject> list = redisson.getList("anyList");
list.add(new SomeObject());
list.get(0);
list.remove(new SomeObject());
  • 1
  • 2
  • 3
  • 4
  • 5

分布式Blocking Queue


RBlockingQueue<SomeObject> queue = redisson.getBlockingQueue("anyQueue");
queue.offer(new SomeObject());
SomeObject obj = queue.peek();
SomeObject someObj = queue.poll();
SomeObject ob = queue.poll(10, TimeUnit.MINUTES);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

除此之外,还支持Queue, Deque, Blocking Deque

其他功能

执行批量命令


RBatch batch = redisson.createBatch();
batch.getMap("test").fastPutAsync("1", "2");
batch.getMap("test").fastPutAsync("2", "3");
batch.getMap("test").putAsync("2", "5");
batch.getAtomicLongAsync("counter").incrementAndGetAsync();
batch.getAtomicLongAsync("counter").incrementAndGetAsync();
List<?> res = batch.execute();


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值