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

如何从Spring RedisTemplate中获得Jedis实例

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2023-03-13
  • 2022-03-07
  • 2021-06-03
猜你喜欢
  • 1970-01-01
  • 2022-12-23
  • 2021-08-02
  • 2021-05-31
  • 2021-11-23
  • 2021-08-07
  • 2021-09-03
相关资源
相似解决方案