package com.elab.redis.redisson;

import com.elab.core.componts.ConcurrentTool;
import com.elab.redis.RedissonApplication;
import com.elab.redis.config.CacheAutoConfiguration;
import com.google.common.util.concurrent.RateLimiter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.*;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RedissonApplication.class, CacheAutoConfiguration.class})
public class RedissonAutoConfigurationTest {

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private RedisTemplate<String, String> template;

    @Test
    public void testApp() {
        redisson.getKeys().flushall();
        RAtomicDouble atomicDouble = redisson.getAtomicDouble("");
        RMap<Object, Object> map = redisson.getMap("", JsonJacksonCodec.INSTANCE);
        RMap<String, String> m = redisson.getMap("test", StringCodec.INSTANCE);
        m.put("1", "2");
        BoundHashOperations<String, String, String> hash = template.boundHashOps("test");
        String t = hash.get("1");
        assertThat(t).isEqualTo("2");
    }

    @Test
    public void reteLimiterCase() throws Exception {
        //        ConcurrentTool concurrentTool = new ConcurrentTool(10);
        //        //{liukx}
        //        RRateLimiter rateLimiter = redisson.getRateLimiter("myRateLimiter");
        //        boolean trySetRate = rateLimiter.trySetRate(RateType.OVERALL, 5, 2, RateIntervalUnit.SECONDS);
        //        concurrentTool.process(() -> {
        //
        //            System.out.println(trySetRate);
        //            rateLimiter.acquire(1);
        //            return trySetRate;
        //        });

        RRateLimiter rateLimiter = redisson.getRateLimiter("abc_{myRateLimiter}");

        if (rateLimiter.isExists()) {
            // 初始化
            // 最大流速 = 每1秒钟产生10个令牌
            rateLimiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.SECONDS);
        }
        CountDownLatch latch = new CountDownLatch(2);
        rateLimiter.acquire(3);
        // ...

        Thread t = new Thread(() -> {
            rateLimiter.acquire(2);
            // ...
        });
        System.in.read();
    }

}