項目組同事提出一個問題,使用Spring RestTemplate不能在“不存在時設值”的同時,設置超時時間。我通過閱讀源代碼,發現Jedis是支持這一指令的,以下代碼來自於 redis.clients.jedis.Jedis
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
* @param key
* @param value
* @param nxxx NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the key if it already exist.
* @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds
* @param time expire time in the units of <code>expx</code>
* @return Status code reply
*/
public String set(final String key, final String value, final String nxxx, final String expx, final long time) {
而RestTemplate在封裝時,忽略了返回值。這個返回值表示了設值是否成功,在分佈式鎖等應用場景中是非常重要的。以下代碼來自於org.springframework.data.redis.connection.RedisStringCommands
/**
* Set {@code value} for {@code key} applying timeouts from {@code expiration} if set and inserting/updating values
* depending on {@code option}.
*
* @param key must not be {@literal null}.
* @param value must not be {@literal null}.
* @param expiration can be {@literal null}. Defaulted to {@link Expiration#persistent()}.
* @param option can be {@literal null}. Defaulted to {@link SetOption#UPSERT}.
* @since 1.7
* @see <a href="http://redis.io/commands/set">Redis Documentation: SET</a>
*/
void set(byte[] key, byte[] value, Expiration expiration, SetOption option);
如何在使用RedisTemplate的同時,獲取Jedis實例,執行相關的方法?以下的方案是從RedisConnectionFactory中獲取Redis連接(JedisConnection實現類),然後使用反射的方法從中取得了Jedis實例,即可直接執行其中的方法,供大家參考
@Autowired
private RedisConnectionFactory connectionFactory;
@RequestMapping("/greeting")
public String greeting() {
Field jedisField = ReflectionUtils.findField(JedisConnection.class, "jedis");
ReflectionUtils.makeAccessible(jedisField);
System.out.println(connectionFactory.getConnection());
Jedis jedis = (Jedis) ReflectionUtils.getField(jedisField, connectionFactory.getConnection());
String result = jedis.set("test-key", "Hello world-", "NX", "EX", 1);
代碼執行後,返回字符串”OK”或者”null”,表示是否設值成功。