boot整合redis

redisTemplate封装

    • pom
    • redisTemplate配置类
    • redis工具类封装

pom

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>

redisTemplate配置类

覆盖默认的redis模板类, 改为String, Object对象

package top.bitqian.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @author echo lovely* @date 2020/12/24 16:07*/@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();// 设置连接工厂template.setConnectionFactory(redisConnectionFactory);// jackson序列化设置Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和publicom.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);jsonRedisSerializer.setObjectMapper(om);// stringStringRedisSerializer stringSerializer = new StringRedisSerializer();// string 的key序列化使用字符串template.setKeySerializer(stringSerializer);template.setValueSerializer(jsonRedisSerializer);template.setHashKeySerializer(stringSerializer);// hash maptemplate.setHashValueSerializer(jsonRedisSerializer);template.afterPropertiesSet();return template;}}

redis工具类封装

package top.bitqian.util;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;/*** @author echo lovely* @date 2020/12/24 16:55*/@Component
public final class RedisUtil01 {@Resourceprivate RedisTemplate<String, Object> redisTemplate;// =============================common============================/*** 指定缓存失效时间** @param key  键* @param time 时间(秒)*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key 获取过期时间** @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断key是否存在** @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存** @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(Arrays.asList(key));}}}// ============================String=============================/*** 普通缓存获取** @param key 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入** @param key   键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间** @param key   键* @param value 值* @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 递增** @param key   键* @param delta 要增加几(大于0)*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减** @param key   键* @param delta 要减少几(小于0)*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}// ================================Map=================================/*** HashGet** @param key  键 不能为null* @param item 项 不能为null*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取hashKey对应的所有键值** @param key 键* @return 对应的多个键值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet** @param key 键* @param map 对应多个键值*/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** HashSet 并设置时间** @param key  键* @param map  对应多个键值* @param time 时间(秒)* @return true成功 false失败*/public boolean hmset(String key, Map<String, Object> map, long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @return true 成功 false失败*/public boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败*/public boolean hset(String key, String item, Object value, long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除hash表中的值** @param key  键 不能为null* @param item 项 可以使多个 不能为null*/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/*** 判断hash表中是否有该项的值** @param key  键 不能为null* @param item 项 不能为null* @return true 存在 false不存在*/public boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/*** hash递增 如果不存在,就会创建一个 并把新增后的值返回** @param key  键* @param item 项* @param by   要增加几(大于0)*/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减** @param key  键* @param item 项* @param by   要减少记(小于0)*/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}// ============================set=============================/*** 根据key获取Set中的所有值** @param key 键*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据value从一个set中查询,是否存在** @param key   键* @param value 值* @return true 存在 false不存在*/public boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {e.printStackTrace();return false;}}/*** 将数据放入set缓存** @param key    键* @param values 值 可以是多个* @return 成功个数*/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 将set数据放入缓存** @param key    键* @param time   时间(秒)* @param values 值 可以是多个* @return 成功个数*/public long sSetAndTime(String key, long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0)expire(key, time);return count;} catch (Exception e) {e.printStackTrace();return 0;}}/*** 获取set缓存的长度** @param key 键*/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 移除值为value的** @param key    键* @param values 值 可以是多个* @return 移除的个数*/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {e.printStackTrace();return 0;}}// ===============================list=================================/*** 获取list缓存的内容** @param key   键* @param start 开始* @param end   结束 0 到 -1代表所有值*/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/*** 获取list缓存的长度** @param key 键*/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 通过索引 获取list中的值** @param key   键* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推*/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {e.printStackTrace();return null;}}/*** 将list放入缓存** @param key   键* @param value 值*/public boolean lSet(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)*/public boolean lSet(String key, Object value, long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @return*/public boolean lSet(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return*/public boolean lSet(String key, List<Object> value, long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据索引修改list中的某条数据** @param key   键* @param index 索引* @param value 值* @return*/public boolean lUpdateIndex(String key, long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 移除N个值为value** @param key   键* @param count 移除多少个* @param value 值* @return 移除的个数*/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {e.printStackTrace();return 0;}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/420404.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端学习(1303):复制文件夹

const gulp require(gulp); const htmlmin require(gulp-htmlmin); const fileinclude require(gulp-file-include); const less require(gulp-less); const csso require(gulp-csso); const babel require(gulp-babel); gulp.task(first, () > {console.log(第一次执…

[另开新坑] 算导v3 #26 最大流 翻译

26 最大流 就像我们可以对一个路网构建一个有向图求最短路一样,我们也可以将一个有向图看成是一个"流量网络(flow network)",用它来回答关于流的问题. Just as we can model a road map as a directed graph in order to find the shortest path from one point to a…

springdata jpa单表操作crud

spring data jpa1. 项目搭建1.1 配置1.2 实体类1.3 继承JpaRepository接口2. 批量新增3. 查询4. 修改 by hql5. 删除 by hql1. 项目搭建 使用boot整合&#xff0c;导入springdata jap, mysql 驱动&#xff0c;lombok&#xff0c;web。 1.1 配置 # boot add jpa, oh~ crud in…

呀~ 一个.java的源文件可以写这么多类啊

1. 外部类 (写在pulic修饰的类外面) 2. 静态内部类(写在类的里面) 3. 局部内部类(写在方法里面) 4. 匿名内部类 5. 函数式接口。lambada表达式。public class LambdaDemo01 {/*** 2. 静态内部类*/static class Love02 implements Lover {Overridepublic void love() {System.ou…

js打开、关闭页面和运行代码那些事

<!doctype html> <html> <head> <meta charset"utf-8"> <meta name"author" content"智能社 - zhinengshe.com"> <meta name"copyright" content"智能社 - zhinengshe.com"> <title…

css定位:相对定位

关于相对定位的结论如下1. 使用相对定位的盒子&#xff0c;会相对于它原来的位置&#xff0c;通过偏移指定的距离&#xff0c;到达新的位置。2.使用相对定位的盒子仍在标准流中&#xff0c;它对父块和兄弟盒子没有任何影响。 <html><head><meta http-equiv”Con…

Vue warn: Invalid prop: type check failed for prop “data“. Expected Array, got Object.

需要数组&#xff0c;但是获取的是对象拉。 但是接口解析处理返回的是数组。 与下面的定义有关。我定义成了对象.png. 正解&#xff1a;

前端学习(1306):node.js模块的加载机制

demo10.js require(./find.js); find.js console.log(找到了); 运行结果

用nodejs 替换文件中所有图片的url

用nodejs 替换文件中所有图片的url 因业务需求&#xff0c;大量文件需要替换url到不同的环境。 所以用nodejs写了这个。本来想用python写&#xff0c;但是大部分同事只有nodejs环境。 主要的命令node rurl.js -new http://www.g.cn/ 替换原有.png .jpg图片图片路劲到 http://ww…

git bash上传大文件到github

git-lfs下载git lfs工具命令GitHub默认最高支持单次上传文件100MB git-lfs&#xff1a;git large file storage 下载git lfs工具 https://git-lfs.github.com/ 命令 在工作目录打开git bash。 # 1. 启用lfsgit lfs install# 2. 要上传的文件&#xff0c;这里指定目录下的…

Linux 命令快捷键

Linux 命令快捷键 tab 自动补齐(有不知道的吗)Ctrlu 删除(剪切)此处至开始所有内容 Ctrlk 删除从光标所在位置到行末 快速命令行 – 快捷方式• history 搜索历史执行过的命令• ctrll 清屏• Reset 刷新终端屏幕&#xff0c;尤其是终端出现字符不清晰或乱码时特管用 (和ctrl …

Git 分支创建并推送到现有仓库

推送方式 本地初始化仓库&#xff0c;创建分支&#xff0c;关联远程仓库&#xff0c;进行推送。 # 将当前目录交给Git管理 git init# 创建分支 dev # git branch dev # git checkout dev git checkout -b dev# 将代码上传本地仓库 git add .# 提交描述 git commit -m hhh# 与…

Oracle Explain Plan,hint解释与示例

Oracle 专业dba博客&#xff1a;http://blog.csdn.net/tianlesoftware Hint 是Oracle 提供的一种SQL语法&#xff0c;它允许用户在SQL语句中插入相关的语法&#xff0c;从而影响SQL的执行方式。因为Hint的特殊作用&#xff0c;所以对于开发人员不应该在代码中使用它&#xff0c…

docker 指定配置文件启动redis

redis启动1. 下载&#xff0c;修改redis.conf文件2. 指定配置文件启动3. 连接redis1. 下载&#xff0c;修改redis.conf文件 下载redis.conf wget http://download.redis.io/redis-stable/redis.conf修改配置 bind 127.0.0.1 # 注释掉这部分&#xff0c;这是限制redis只能本地…

UVa 10820 (打表、欧拉函数) Send a Table

题意&#xff1a; 题目背景略去&#xff0c;将这道题很容易转化为&#xff0c;给出n求&#xff0c;n以内的有序数对(x, y)互素的对数。 分析&#xff1a; 问题还可以继续转化。 根据对称性&#xff0c;我们可以假设x<y&#xff0c;当xy时&#xff0c;满足条件的只有(1, 1)。…