如果你所在项目中用到了redis作为缓存中间件,那么大多数是使用项目本身已有的工具类,直接调用接口来进行读写就行了。但是,即使你一直用得很顺利,我也建议你了解一下其中的一些过程,以免突然的问题带来带来的尴尬。
以下内容直接展现了Java中使用redis作为缓存的工具类RedisUtil实现全过程,包括:
1、 经典双重判空的单例模式;
2、 Redis线程池的初始化;
3、 Java中使用redis的接口封装;
4、 Redis增删接口的简单测试
Maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
采用单例模式提供实例
private static RedisUtil instance = null;
private JedisPool pool;
private JedisPoolConfig config;
/**
* 单例模式
*
* @return
*/
public static RedisUtil getInstance() {
if (instance == null) {
synchronized (RedisUtil.class) {
if (instance == null) {
instance = new RedisUtil();
// 初始化连接池
instance.init();
}
}
}
return instance;
}
Redis连接池的初始化。在项目中连接的IP、端口、超时等待这些设置一般都是以配置的形式实现,这些为了方便我直接写死在代码里面了。
private void init() {
String redisIp = "192.168.1.1"; // redis服务器IP
int redisPort = 6379; // redis端口号
String redisPassWord = "test123"; // redis连接密码
int timeOut = 1000;
config = new JedisPoolConfig();
config.setMaxIdle(10); // 控制pool中最多有多少个连接给空闲状态
config.setMaxTotal(20); // 控制pool中最大连接实例
config.setMaxWaitMillis(1000); // 最大超时等待时间(毫秒)
config.setTestOnBorrow(true); // 获取连接提前验证
config.setTestOnReturn(true); // 归还连接提前验证
pool = new JedisPool(config, redisIp, redisPort, timeOut, redisPassWord);
}
Redis基本操作的接口封装
获取redis连接实例
public Jedis getJedis() {
return pool == null ? null : pool.getResource();
}
设置值
public String set(String key, String value) {
String result = null;
if (pool == null) {
init();
}
Jedis resource = pool.getResource();
try {
result = resource.set(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {
resource.close();
}
}
return result;
}
带缓存时间的设置值
public String setex(String key, String value, int second) {
String result = null;
if (pool == null) {
init();
}
Jedis resource = pool.getResource();
try {
result = resource.setex(key,second, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {
resource.close();
}
}
return result;
}
根据key删除缓存
public long delete(String key){
long result = 0l;
if (pool == null) {
init();
}
Jedis resource = pool.getResource();
try {
result = resource.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {
resource.close();
}
}
return result;
}
使用main函数进行简单的测试
public static void main(String[] args) {
Jedis jedis = RedisUtil.getInstance().getJedis();
String key = "today";
jedis.set(key,"a nice day");
System.out.println(jedis.get(key));
jedis.del(key);
System.out.println(jedis.del(key));
}
如果觉得文章对你有帮助,欢迎微信关注【白话Java】,一个致力于让编程更加通俗易懂的地方
回复“8080”收获福利