今天,日月教大家如何存储数据到redis的指定db中,熟悉redis的都知道,redis默认是有16个db的,如图:
上图中redis图形化管理工具安装请查看:Redis管理工具TreeNMS
OK,为了节省时间,我们直接在之前的 springBoot集成redis 该项目基础上修改。
一、修改RedisUtils
新增三个方法:
/**
*
* @Title: set
* @Description: 写入缓存并指定库
* @param key
* @param value 为对象时flag_json必须为true
* @param db 缓存的数据库
* @param flag_json 是否将value值转为json
* @param timeOut 时效(秒) 永久传null
* @return boolean
*/
public boolean set(final String key, Object value,int db,boolean flag_json,Long timeOut) {
boolean result = false;
try {
RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
DefaultStringRedisConnection stringRedisConnection = new DefaultStringRedisConnection(redisConnection);
stringRedisConnection.select(db);
if(flag_json){
stringRedisConnection.set(key, JsonUtils.object2Json(value));
}else{
stringRedisConnection.set(key, value.toString());
}
if(timeOut != null && timeOut != 0){
stringRedisConnection.expire(key, timeOut);
}
stringRedisConnection.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
* @Title: get
* @Description: 读取指定db的缓存
* @param key
* @param db
* @return Object
*/
public Object get(final String key,int db) {
Object result = null;
try {
RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
DefaultStringRedisConnection stringRedisConnection = new DefaultStringRedisConnection(redisConnection);
stringRedisConnection.select(db);
result = stringRedisConnection.get(key);
stringRedisConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除指定db的key
*
* @param key
* @param db
*/
public void remove(final String key ,int db) {
try {
RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
DefaultStringRedisConnection stringRedisConnection = new DefaultStringRedisConnection(redisConnection);
stringRedisConnection.select(db);
if(stringRedisConnection.exists(key)){
stringRedisConnection.del(key);
}
stringRedisConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二、controller添加测试请求
/**
*
* @Title: saveCache
* @Description: redis 指定db存储测试
* @param db
* @return String
*/
@RequestMapping(value = "/saveCache/{db}")
public String saveCache(@PathVariable("db") int db){
redisUtils.set("test", "我存储在redis的db " + db, db, false, null);
return redisUtils.get("test", db).toString();
}
三、测试
我们先将redis中db1至db3中的数据清空
打开浏览器,分别请求:
localhost:8002/saveCache/1
localhost:8002/saveCache/2
localhost:8002/saveCache/3
OK,可以看到,测试成功,数据成功存储到指定的db中了。
如果该文章有帮助到您,就点个赞吧!您的支持与肯定是我持续更新最大的动力。