从Spring RedisTemplate中获得Jedis实例

半兽人 发表于: 2019-01-22   最后更新时间: 2021-11-30 10:14:18  
{{totalSubscript}} 订阅, 8,359 游览

使用SpringRestTemplate不能在“不存在时设值”的同时,设置超时时间。我通过阅读源代码,发现Jedis是支持这一指令的,直接上代码:

import com.system.cloud.Application;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ReflectionUtils;
import redis.clients.jedis.Jedis;

import java.lang.reflect.Field;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class RedisManagerTest {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    public void test(){
        Field jedisField = ReflectionUtils.findField(JedisConnection.class, "jedis");
        ReflectionUtils.makeAccessible(jedisField);
        System.out.println(redisTemplate.getConnectionFactory().getConnection());
        Jedis jedis = (Jedis) ReflectionUtils.getField(jedisField, redisTemplate.getConnectionFactory().getConnection());
        String result = jedis.set("test-key", "Hello world-", "NX", "EX", 1);
        System.out.println(result);

        String results = jedis.set("test-key", "Hello world-", "NX", "EX", 1);
        System.out.println(results);
        RedisConnection jedisConnection = redisTemplate.getConnectionFactory().getConnection();
    }
}
更新于 2021-11-30

查看redis更多相关的文章或提一个关于redis的问题,也可以与我们一起分享文章