1. 程式人生 > >如何從Spring RedisTemplate中獲得Jedis例項

如何從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();
	}
}

在這裡插入圖片描述