如何从Spring RedisTemplate中获得Jedis实例
1.1 场景:
在开发项目的时候,习惯使用Jedis操作redis,但如果我们用Spring boot框架,它已经帮我们整合好了redis缓存操作类,具体看RedisAutoConfiguration类,此时我们想获得Jedis操作redis怎么办????
1.1. 实现
public class RedisUtils implements InitializingBean{
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
private JedisPool jedisPool;
public Jedis getJedis() throws Exception {// 记的关闭jedis
if(jedisPool != null) {
return jedisPool.getResource();
} else {
afterPropertiesSet();
return jedisPool.getResource();
}
}
@Override
public void afterPropertiesSet() throws Exception {
Field poolField = ReflectionUtils.findField(JedisConnectionFactory.class, "pool");
ReflectionUtils.makeAccessible(poolField);
jedisPool = (JedisPool) ReflectionUtils.getField(poolField, jedisConnectionFactory);
}
}
1.2 测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes=com.gz.ClientApplication.class)
public class TestCase {
@Autowired
private RedisUtils redisUtils;
@Test
public void test() throws Exception {
Jedis jedis = redisUtils.getJedis();
jedis.set("test","test");
jedis.close();
}
}