redistemplate优雅地操作redis redis 工具类
参考:https://www.cnblogs.com/superfj/p/9232482.html
redis 工具类
package com.service; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.Collection;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream; @Component
public class RedisService {
@Autowired
private RedisTemplate<String, String> redisTemplate; /**
* 默认过期时长,单位:秒
*/
public static final long DEFAULT_EXPIRE = * * ; /**
* 不设置过期时长
*/
public static final long NOT_EXPIRE = -; public boolean existsKey(String key) {
return redisTemplate.hasKey(key);
} /**
* 重名名key,如果newKey已经存在,则newKey的原值被覆盖
*
* @param oldKey
* @param newKey
*/
public void renameKey(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
} /**
* newKey不存在时才重命名
*
* @param oldKey
* @param newKey
* @return 修改成功返回true
*/
public boolean renameKeyNotExist(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
} /**
* 删除key
*
* @param key
*/
public void deleteKey(String key) {
redisTemplate.delete(key);
} /**
* 删除多个key
*
* @param keys
*/
public void deleteKey(String... keys) {
Set<String> kSet = Stream.of(keys).map(k -> k).collect(Collectors.toSet());
redisTemplate.delete(kSet);
} /**
* 删除Key的集合
*
* @param keys
*/
public void deleteKey(Collection<String> keys) {
Set<String> kSet = keys.stream().map(k -> k).collect(Collectors.toSet());
redisTemplate.delete(kSet);
} /**
* 设置key的生命周期
*
* @param key
* @param time
* @param timeUnit
*/
public void expireKey(String key, long time, TimeUnit timeUnit) {
redisTemplate.expire(key, time, timeUnit);
} /**
* 指定key在指定的日期过期
*
* @param key
* @param date
*/
public void expireKeyAt(String key, Date date) {
redisTemplate.expireAt(key, date);
} /**
* 查询key的生命周期
*
* @param key
* @param timeUnit
* @return
*/
public long getKeyExpire(String key, TimeUnit timeUnit) {
return redisTemplate.getExpire(key, timeUnit);
} /**
* 将key设置为永久有效
*
* @param key
*/
public void persistKey(String key) {
redisTemplate.persist(key);
} }
redis的key工具类
package com.util; /**
* redisKey设计
*/
public class RedisKeyUtil { /**
* redis的key
* 形式为:
* 表名:主键名:主键值:列名
*
* @param tableName 表名
* @param majorKey 主键名
* @param majorKeyValue 主键值
* @param column 列名
* @return
*/
public static String getKeyWithColumn(String tableName,String majorKey,String majorKeyValue,String column){
StringBuffer buffer = new StringBuffer();
buffer.append(tableName).append(":");
buffer.append(majorKey).append(":");
buffer.append(majorKeyValue).append(":");
buffer.append(column);
return buffer.toString();
}
/**
* redis的key
* 形式为:
* 表名:主键名:主键值
*
* @param tableName 表名
* @param majorKey 主键名
* @param majorKeyValue 主键值
* @return
*/
public static String getKey(String tableName,String majorKey,String majorKeyValue){
StringBuffer buffer = new StringBuffer();
buffer.append(tableName).append(":");
buffer.append(majorKey).append(":");
buffer.append(majorKeyValue).append(":");
return buffer.toString();
}
}
测试类:
测试类: package com.config; import com.domain.UserVo;
import com.service.RedisService;
import com.util.RedisKeyUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.Set;
import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class RedisConfigTest { @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate redisTemplate; @Resource
private ValueOperations<String,Object> valueOperations; @Autowired
private HashOperations<String, String, Object> hashOperations; @Autowired
private ListOperations<String, Object> listOperations; @Autowired
private SetOperations<String, Object> setOperations; @Autowired
private ZSetOperations<String, Object> zSetOperations; @Resource
private RedisService redisService; @Test
public void testObj() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("上海");
userVo.setName("测试dfas");
userVo.setAge();
ValueOperations<String,Object> operations = redisTemplate.opsForValue();
redisService.expireKey("name",, TimeUnit.SECONDS);
String key = RedisKeyUtil.getKey(UserVo.Table,"name",userVo.getName());
UserVo vo = (UserVo) operations.get(key);
System.out.println(vo);
} @Test
public void testValueOption( )throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("上海");
userVo.setName("jantent");
userVo.setAge();
valueOperations.set("test",userVo); System.out.println(valueOperations.get("test"));
} @Test
public void testSetOperation() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge();
UserVo auserVo = new UserVo();
auserVo.setAddress("n柜昂周");
auserVo.setName("antent");
auserVo.setAge();
setOperations.add("user:test",userVo,auserVo);
Set<Object> result = setOperations.members("user:test");
System.out.println(result);
} @Test
public void HashOperations() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge();
hashOperations.put("hash:user",userVo.hashCode()+"",userVo);
System.out.println(hashOperations.get("hash:user",userVo.hashCode()+""));
} @Test
public void ListOperations() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge();
// listOperations.leftPush("list:user",userVo);
// System.out.println(listOperations.leftPop("list:user"));
// pop之后 值会消失
System.out.println(listOperations.leftPop("list:user"));
}
} 注解缓存的使用 @Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;没有则调用方法并将方法返回值放进缓存。 @CachePut:将方法的返回值放到缓存中。 @CacheEvict:删除缓存中的数据。 最后所有的代码都被上传到我的github喜欢的话,给个start
注解缓存的使用
@Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;没有则调用方法并将方法返回值放进缓存。
@CachePut:将方法的返回值放到缓存中。
@CacheEvict:删除缓存中的数据。
最后所有的代码都被上传到我的github喜欢的话,给个start
redistemplate优雅地操作redis redis 工具类的更多相关文章
- 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...
- spring boot 结合Redis 实现工具类
自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...
- 操作集合的工具类Collections
1 操作集合的工具类Collections Java提供了一个操作Set.List和Map等集合的工具类:Collections,该工具类里提供了大量方法对集合元素进行排序.查询和修改等操 ...
- Java操作字符串的工具类
操作字符串的工具类 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStre ...
- Java操作图片的工具类
操作图片的工具类: import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.a ...
- 【转载】C#工具类:实现文件操作File的工具类
在应用程序的开发中,文件操作的使用基本上是必不可少的,FileStream类.StreamWriter类.Directory类.DirectoryInfo类等都是文件操作中时常涉及到的类,我们可以通过 ...
- c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习
c#中@标志的作用 参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...
- 自定义的操作Cookie的工具类
可以在SpringMVC等环境中使用的操作Cookie的工具类 package utils; import java.io.UnsupportedEncodingException; import j ...
- java里poi操作excel的工具类(兼容各版本)
转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...
- Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类
FileService.java也就是操作sdcard的工具类: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ...
随机推荐
- 【git】之常用命令
再使用git过程常用的命令在6-10左右,但是如果你想精通git那么需要记住的命令在80左右, 下面看这张图,我们了解一下git的概念的常用操作! Workspace:工作区(例如eclipse的工作 ...
- awk中使用shell的环境变量
awk中使用shell的环境变量一:"'$var'"这种写法大家无需改变用'括起awk程序的习惯,是老外常用的写法.如:var="test"awk 'BEGIN ...
- STL进阶--vector vs deque
vector class Dog; // 例 1: vector<Dog> vec(6); // vec.capacity() == 6, vec.size() == 6, // 默认构造 ...
- pandas.DataFrame 插入列和行
转载:www.360doc.com/content/17/0225/23/1489589_632032302.shtml 以csv实例文件操作插入DataFrame的行和列 文件名:example.c ...
- http系列(一)
一.关于Url URI由URL和URN组成,URI即统一资源标识符,URL即统一资源定位符,URN即统一资源名称. 现在最常用的是URL. 二.http请求/响应报文 请求报文:请求行.请求头部.空行 ...
- Linux下的文件操作——基于文件描述符的文件操作(2)
文件描述符的复制 MMAP文件映射 ftruncate修改文件大小 文件描述符的复制 系统调用函数dup和dup2可以实现文件描述符的复制,经常用来重定向进程的stdin(0), stdout(1 ...
- 构建Redis主从镜像
构建Redis的基础镜像,然后基于这个基础镜像构建主Redis镜像和从Redis镜像. 1.构建Redis基础镜像 创建redis基础镜像目录 [root@localhost mnt]# mkdir ...
- 制作OpenStack云平台centos6.5镜像
创建虚拟镜像 # qemu-img create -f raw Cloud_Centos6.5_64bit.img 10G [root@localhost ~]# ll /opt/CentOS-6.5 ...
- springMVC的执行流程和完整代码
一.什么是 Spring MVC Spring MVC 属于 SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 里面,是一个强大灵活的 Web 框架.Spring ...
- 获取Android文件路径
Environment.getDataDirectory().getPath() : /data Environment.getDownloadCacheDirectory().getPath() : ...