Jedis连接池简易操作Redis工具类

本文内容如有错误、不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢。

简述

引入依赖

在Spring 项目中引入下面依赖:

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
</dependency>

redis配置信息

在 Spring 项目的配置文件 application.yml 配置如下信息:

#reids
redis:
    host: 127.0.0.1
    port: 6379
    auth:
    max-idle: 5
    max-total: 10
    max-wait-millis: 3000

Jedis连接池包装类

自定义包装类 JedisPoolWrapper.java 便于获取连接池。

@Component
@Slf4j
public class JedisPoolWrapper {


	private JedisPool jedisPool = null;
	
	@Autowired
	private Parameters parameters;
	/**
	  * 在初始化后,项目完全启动之前执行
	  **/
	@PostConstruct
	public void init() throws MyApplicationException {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(parameters.getRedisMaxTotal());
			config.setMaxIdle(parameters.getRedisMaxIdle());
			config.setMaxWaitMillis(parameters.getRedisMaxWaitMillis());

			jedisPool = new JedisPool(config,parameters.getRedisHost(),parameters.getRedisPort(),2000,parameters.getRedisAuth());
		} catch (Exception e) {
			log.error("Fail to initialize jedis pool", e);
			throw new MyApplicationException("Fail to initialize jedis pool");
		}
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}
	
}

其中需要注入 Parameters Bean 到容器中,这里的 Parameters 主要是获取对应配置文件 application.yml 文件中对应的信息,为方便统一管理方才手动编写 Parameters 类。

Parameters

项目中需要用到的配置,统一管理类:
Parameters.java

/**
 * 系统参数
 */
@Component
@Data
public class Parameters {
    /*****redis config start*******/
    @Value("${redis.host}")
    private String redisHost;
    @Value("${redis.port}")
    private int redisPort;
    @Value("${redis.auth}")
    private String redisAuth;
    @Value("${redis.max-idle}")
    private int redisMaxTotal;
    @Value("${redis.max-total}")
    private int redisMaxIdle;
    @Value("${redis.max-wait-millis}")
    private int redisMaxWaitMillis;
    /*****redis config end*******/

}

简易操作Redis工具类

CommonCacheUtil.java

@Component
@Slf4j
public class CommonCacheUtil {


	private static final String TOKEN_PREFIX = "token.";
	
	private static final String USER_PREFIX = "user.";


	@Autowired
	private JedisPoolWrapper jedisPoolWrapper;

	/**
	 * 缓存 可以value 永久
	 * @param key
	 * @param value
	 */
	public void cache(String key, String value) {
		try {
			JedisPool pool = jedisPoolWrapper.getJedisPool();
			if (pool != null) {
				try (Jedis Jedis = pool.getResource()) {
					Jedis.select(0);
					Jedis.set(key, value);
				}
			}
		} catch (Exception e) {
			log.error("Fail to cache value", e);
		}
	}

	/**
	 * 获取缓存key
	 * @param key
	 * @return
	 */
	public String getCacheValue(String key) {
		String value = null;
		try {
			JedisPool pool = jedisPoolWrapper.getJedisPool();
			if (pool != null) {
				try (Jedis Jedis = pool.getResource()) {
					Jedis.select(0);
					value = Jedis.get(key);
				}
			}
		} catch (Exception e) {
			log.error("Fail to get cached value", e);
		}
		return value;
	}

	/**
	 * 设置key value 以及过期时间
	 * @param key
	 * @param value
	 * @param expiry
	 * @return
	 */
	public long cacheNxExpire(String key, String value, int expiry) {
		long result = 0;
		try {
			JedisPool pool = jedisPoolWrapper.getJedisPool();
			if (pool != null) {
				try (Jedis jedis = pool.getResource()) {
					jedis.select(0);
					result = jedis.setnx(key, value);
					jedis.expire(key, expiry);
				}
			}
		} catch (Exception e) {
			log.error("Fail to cacheNx value", e);
		}
		
		return result;
	}

	/**
	 * 删除缓存key
	 * @param key
	 */
	public void delKey(String key) {
		JedisPool pool = jedisPoolWrapper.getJedisPool();
		if (pool != null) {

			try (Jedis jedis = pool.getResource()) {
				jedis.select(0);
				try {
					jedis.del(key);
				} catch (Exception e) {
					log.error("Fail to remove key from redis", e);
				}
			}
		}
	}
}

结论

通过上面的简单介绍,相信已经可以基本了解到如何通过自定义构建连接池封装类和工具类进行一定操作,当然还有许多功能可以添加到工具类中,等待你的开发。

发布了56 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/feng_xiaoshi/article/details/103833356