Redis客户端Redisson使用示例

Redis客户端Redisson使用示例

  1. Redisson作为Java连接Redis的客户端,提供了连接、操作Redis的方法,还提供分布式锁、红锁等并发工具。Redisson除了提供同步接口外,还提供了异步(Async)、反射式(Reactive)和RxJava2标准的接口。Redisson会序列化Java对象然后保存到redis,所以通过redis命令行设置的值,Redisson来获取值会报错。
  2. 引入maven依赖包

<dependency>
    <groupId>org.redissongroupId>
    <artifactId>redissonartifactId>
    <version>3.16.0version>
dependency>
  1. Redisson初始化连接
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.redisson.client.RedisClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;

@RunWith(Junit4.class)
public class RedissonCase {
    
    private RedissonClient redissonClient;
    private RedissonReactiveClient reactiveClient;
    private RedissonRxClient rxClient;
    
    @Before
    public void init() {
        //单节点配置
    	Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://localhost:6379")
                .setPassword("123456")
                .setConnectionPoolSize(5)
                .setConnectionMinimumIdleSize(2)
                .setDatabase(0);
        redissonClient = Redisson.create(config);
        reactiveClient = Redisson.createReactive(config);
        rxClient = Redisson.createRx(config);    
    }    
    
    @After
    public void destroy(){
        redissonClient.shutdown();
        reactiveClient.shutdown();
        rxClient.shutdown();
    }
}
  1. 使用通用对象桶,可以存放任何类型对象
@Test
public void bucket() throws Exception {
    //同步
    RBucket<String> bucket = redissonClient.getBucket("name");
    bucket.set("郑禹");
    System.out.println(bucket.get());
    //异步
    RBucket<String> bucket2 = redissonClient.getBucket("name2");
    bucket2.setAsync("刘晓雪").get();
    bucket2.getAsync().thenAccept(System.out::println);
    //Reactive
    RBucketReactive<String> bucket3 = reactiveClient.getBucket("name3");
    bucket3.set("张佳慧").block();
    bucket3.get().subscribe(System.out::println);
    //RxJava2 没有读取到值
    RBucketRx<String> bucket4 = rxClient.getBucket("name4");
    bucket4.set("刘万敏").blockingSubscribe(System.out::println);
    Thread.sleep(1000 * 5);
}

执行结果:

郑禹
刘晓雪
张佳慧

  1. 清空桶可以给键设置过期时间,或者直接删除键。
@Test
public void clearBucket() {
    RBucket<String> bucket = redissonClient.getBucket("name2", new JsonJacksonCodec());
    bucket.set("刘晓雪", 60, TimeUnit.SECONDS);
    boolean deleteFlag = bucket.delete();
    assertEquals(true, deleteFlag);    
}
  1. 流操作
@Test
public void stream() throws Exception {
    RBinarySream stream = redissonClient.getBinaryStream("stream");
    stream.set("汪稳".getBytes());
    OutputStream outputStream = stream.getOutputStream();
    outputStream.write("和钱晨馨".getBytes());
    InputStream inputStream = stream.getInputStream();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int len;
    while((len=inputStream.read(b)) != -1) {
        result.write(b, 0, len);
    }
    System.out.println(result.toString());
}

执行结果:

汪稳和钱晨馨

  1. 原子整型示例,设置初始值10,先自增后返回。
@Test
public void atomicLong() {
    RAtomicLong atomicLong = redissonClient.getAtomicLong("atomicLong");
    atomicLong.set(10);
    atomicLong.incrementAndGet();
    System.out.println(atomicLong);
}

执行结果:

11

  1. 限流器,初始化最大流速,每秒生成5个令牌。
@Test
public void rateLimit() throws Exception {
    RRateLimiter rateLimiter = redissonClient.getRateLimiter("rateLimiter");
    rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.SECONDS);
    for (int i=0;i<10;i++) {
        new Thread(new Runnable() {
            int i = 0;
            
            @Override
            public void run() {
                while(true) {
                    rateLimiter.acquire(1);
                    System.out.println(Thread.currentThread() + "-" + System.currentTimeMillis() + "-" + i++);
                }
            }
        }).start();
    }
    Thread.sleep(1000 * 5);
}

执行结果:

Thread[Thread-1,5,main]-1683092928431-0
Thread[Thread-2,5,main]-1683092928434-0
Thread[Thread-4,5,main]-1683092928441-0
Thread[Thread-10,5,main]-1683092928441-0
Thread[Thread-8,5,main]-1683092928442-0
Thread[Thread-10,5,main]-1683092929434-1
Thread[Thread-8,5,main]-1683092929434-1
Thread[Thread-4,5,main]-1683092929434-1
Thread[Thread-10,5,main]-1683092929437-2
Thread[Thread-4,5,main]-1683092929437-2
Thread[Thread-10,5,main]-1683092930449-3
Thread[Thread-1,5,main]-1683092930450-1
Thread[Thread-7,5,main]-1683092930450-0
Thread[Thread-8,5,main]-1683092930450-2
Thread[Thread-2,5,main]-1683092930449-1
Thread[Thread-8,5,main]-1683092931469-3
Thread[Thread-7,5,main]-1683092931471-1
Thread[Thread-5,5,main]-1683092931471-0
Thread[Thread-2,5,main]-1683092931472-2
Thread[Thread-1,5,main]-1683092931472-2
Thread[Thread-8,5,main]-1683092932458-4
Thread[Thread-1,5,main]-1683092932459-3
Thread[Thread-4,5,main]-1683092932461-3
Thread[Thread-5,5,main]-1683092932461-1
Thread[Thread-2,5,main]-1683092932461-3

  1. 列表操作
@Test
public void list() {
    RList<String> list = redissonClient.getList("list");
    list.add("big");
    list.add("宋茜");
    list.add("高圆圆");
    list.remove(1);
    System.out.println(list);
}

执行结果:

[big, 高圆圆]

  1. map字典操作
@Test
public void map() {
    RMap<String, String> map = redissonClient.getMap("map");
    map.put("name", "张飞");
    map.put("location", "南京");
    map.forEach((key, vlaue) -> {
       System.out.println("key=" + key + ",value=" + value); 
    });
}

执行结果:

key=name,value=张飞
key=location,value=南京

  1. 元素不可重复set集合
@Test
public void set(){
    RSet<String> set = redissonClient.getSet("set");
    set.add("汪稳");
    set.add("汪新建");
    set.forEach(System.out::println);
}
  1. 队列示例
@Test
public void queue() {
    RQueue<String> queue = redissonClient.getQueue("queue");
    queue.add("钱晨馨");
    queue.add("汪稳");
    System.out.println(queue.size() + ":" + queue.poll());
    queue.clear();
}

执行结果:

2:钱晨馨

  1. 可重入锁实现
@Test
public void lock throws InterruptedException {
    RLock lock = redissonClient.getLock("lock");
    for (int i=0;i<5;i++) {
        new Thread(()-> {
            lock.lock();
            lock.lock();
            try {
                System.out.println(Thread.currentThread() + "-" + System.currentTimeMillis() + "-" + "获取了锁");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }
    Thread.sleep(5000);
}

你可能感兴趣的:(#,NoSQL,redis,junit,java)