使用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();
}
}