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 ...
随机推荐
- eclipse 修改 项目的git地址
在项目的隐藏目录.git 文件夹下面 修改config配置文件 [core] symlinks = false repositoryformatversion = 0 filemode = false ...
- 【maven】之打包war依赖子项目jar
比如 p-common p-core p-dao p-service p-web service项目依赖dao,dao依赖core和common,web依赖service 在使用maven tomca ...
- 使用模板引擎artTemplate的几个问题总结
一.Template not found 有的时候模板写的并没有问题,可就是找不到.这时候可能是<script>加载顺序问题,模板渲染在模板加载完成之前先执行了,调整<script& ...
- [UE4]Reliable,可靠性
1.Reliable,不会丢失,立刻发出,适合重要的事件 2.Unreliable,可能会丢失,适合表现相关的和不重要的事件 3.全部的远程调用都使用Reliable,可能会造成网络拥堵 4.尽量避免 ...
- android adb push 命令
1.获得root权限:adb root 2.设置/system为可读写:adb remount 3.将PC机上文件复制到手机:adb push 文件名 /system/lib
- Js学习(1)
数据类型 简单数据类型 ◆number 数字类型 ◆string 字符串类型 ◆Boolean 布尔类型 ◆true 真 (正确的) ◆false 假(错误的) ◆u ...
- c#day02
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace testmys ...
- logstash报错401 需要在logstash启动的配置文件中增加es的用户名和密码
- Ext.NET Ext.JS 常用代码片段摘录
引言 最近写代码突然有"一把梭"的感觉, 不管三七二十一先弄上再说. 换别人的说法, 这应该是属于"做项目"风格法吧. 至于知识体系, 可以参考官方或者更权威的 ...
- socketsever
socketsever 一个集成了TCP.UDP多线程多进程高并发的socket框架,可以用来快速搭建socket应用,并且拥有较好的并发性能. import socketserver class M ...