作用:RBucket桶可存储任意对象,可在高并发场景下进行唯一更新。
示例:创建20个线程并发更新桶对象,只有一个执行了更新操作。
先添加redisson的依赖。
org.redissonredisson3.20.0
public static void main(String[] args) {Config config = new Config();config.useSingleServer().setAddress("redis://localhost:6379").setPassword("123456");RedissonClient client = Redisson.create(config);RCountDownLatch countDownLatch = client.getCountDownLatch("countDownLatch");countDownLatch.trySetCount(20);RBucket bucket = client.getBucket("bucket");bucket.set("桶测试"+1);String oldValue=bucket.get();ExecutorService executorService= Executors.newFixedThreadPool(20);for (int i=0;i {System.out.println("线程:" + Thread.currentThread().getId() + ",桶:" + bucket.get());if (bucket.compareAndSet(oldValue, "桶测试 " + 2)) {System.out.println("线程" + Thread.currentThread().getId() + "更新了bucket的值");}countDownLatch.countDown();});}try {countDownLatch.await();}catch (Exception e){e.printStackTrace();}System.out.println("更新后的桶对象为:"+bucket.get());executorService.shutdown();}
接口文档:
public interface RBucket extends RExpirable, RBucketAsync { void set(V var1);//设置桶存储的对象void set(V var1, long var2, TimeUnit var4);//设置桶存储的对象,设置操作的超时时间var2 boolean trySet(V var1);//尝试设置桶的新值boolean trySet(V var1, long var2, TimeUnit var4);//尝试设置桶的新值,设置超时时间var2 boolean compareAndSet(V var1, V var2); //原子替换桶的新值为var2 long size(); //桶存储对象的大小 V get(); //返回桶存储的对象V getAndDelete();//返回并删除桶存储的对象 V getAndSet(V var1); //返回桶的旧值,设置新值V getAndSet(V var1, long var2, TimeUnit var4); //返回桶的旧值,设置新值,设置操作的超时时间var2 }