package com.elab.redis.redisson.doc;

import com.elab.redis.RedisSpringBoot;
import com.elab.redis.redisson.doc.model.SomeObject;
import org.junit.Test;
import org.redisson.api.RFuture;
import org.redisson.api.RMap;
import org.redisson.api.RMapCache;

import java.util.concurrent.TimeUnit;

/**
 * 分布式集合操作
 *
 * @author ： liukx
 * @time ： 2020/7/9 - 16:37
 */
public class DistributedCollectionsTest extends RedisSpringBoot {


    @Test
    public void mapTest() {
        RMap<String, SomeObject> map = client.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");

        RFuture<SomeObject> putAsyncFuture = map.putAsync("321", new SomeObject());
        RFuture<Boolean> fastPutAsyncFuture = map.fastPutAsync("321", new SomeObject());

        map.fastPutAsync("321", new SomeObject());
        map.fastRemoveAsync("321");
    }

    @Test
    public void lockMapTest() {
//        RMap<MyKey, MyValue> map = client.getMap("anyMap");
//        MyKey k = new MyKey();
//        RLock keyLock = map.getLock(k);
//        keyLock.lock();
//        try {
//            MyValue v = map.get(k);
//            // 其他业务逻辑
//        } finally {
//            keyLock.unlock();
//        }
//
//        RReadWriteLock rwLock = map.getReadWriteLock(k);
//        rwLock.readLock().lock();
//        try {
//            MyValue v = map.get(k);
//            // 其他业务逻辑
//        } finally {
//            keyLock.readLock().unlock();
//        }
    }

    @Test
    public void evictionMapTest() {
        RMapCache<String, SomeObject> map = client.getMapCache("anyMap");
        // 有效时间 ttl = 10分钟
        map.put("key1", new SomeObject("1"), 10, TimeUnit.MINUTES);
        // 有效时间 ttl = 10分钟, 最长闲置时间 maxIdleTime = 10秒钟
        map.put("key1", new SomeObject("1"), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);

        // 有效时间 = 3 秒钟
        map.putIfAbsent("key2", new SomeObject("2"), 3, TimeUnit.SECONDS);
        // 有效时间 ttl = 40秒钟, 最长闲置时间 maxIdleTime = 10秒钟
        map.putIfAbsent("key2", new SomeObject("2"), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
    }
}
