整体结构

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.cc</groupId><artifactId>spring-redis</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-redis</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

RedisConfig

package com.cc.springredis.config;import com.cc.springredis.RedisUtil;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {/*** 实例化 RedisTemplate 对象** @return*/@Beanpublic RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();initDomainRedisTemplate(redisTemplate, redisConnectionFactory);return redisTemplate;}/*** 设置数据存入 redis 的序列化方式,并开启事务** @param redisTemplate* @param factory*/private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {//如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!  redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());// 开启事务redisTemplate.setEnableTransactionSupport(true);redisTemplate.setConnectionFactory(factory);}/*** @return RedisUtil* @throws* @Title: redisUtil*/@Bean(name = "redisUtil")public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {RedisUtil redisUtil = new RedisUtil();redisUtil.setRedisTemplate(redisTemplate);return redisUtil;}}

RedisUtil

package com.cc.springredis;import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;public class RedisUtil {private RedisTemplate<String, Object> redisTemplate;public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {this.redisTemplate = redisTemplate;}// =============================common============================/*** 指定缓存失效时间* * @param key 键* @param time  时间(秒)* @return*/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(CollectionUtils.arrayToList(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 by 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减* * @param key   键* @param by 要减少几(小于0)* @return*/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* @return 值*/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  对应多个键值* @return true 成功 false 失败*/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)* @return*/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减* * @param key 键* @param item 项* @param by 要减少记(小于0)* @return*/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}// ============================set=============================/*** 根据key获取Set中的所有值* * @param key 键* @return*/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 键* @return*/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代表所有值* @return*/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  键* @return*/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倒数第二个元素,依次类推* @return*/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  值* @return*/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   时间(秒)* @return*/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;}}
}

测试类SpringRedisApplicationTests

package com.cc.springredis;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import javax.annotation.Resource;@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringRedisApplication.class)
public class SpringRedisApplicationTests {@Resourceprivate RedisUtil redisUtil;@Testpublic void testRedis() {redisUtil.set("test", "1111111111");System.out.println(redisUtil.get("test"));}}

application.properties


########################################################
###REDIS (RedisProperties) redis基本配置;
########################################################
# database name
spring.redis.database=0
# server host1 单机使用,对应服务器ip
spring.redis.host=192.168.133.130
# server password 密码,如果没有设置可不配
#spring.redis.password=
#connection port  单机使用,对应端口号
spring.redis.port=10190
# pool settings ...池配置
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

Redis整合Springboot实现单机配置相关推荐

  1. Redis整合SpringBoot,出现“\xac\xed\x00\x05t\x00\x03解决自定义RedisTemplate序列化

    SpringBoot整合 SpringBoot操作数据:spring-data jpa jdbc mongodb redis SpringData也是和SpringBoot齐名的项目 说明:在Spri ...

  2. Redis整合springboot实现消息队列

    publisher消息的发出 代码整体的结构 publisherConfig package com.cc.springbootredispublisher.config;import org.spr ...

  3. Redis整合springboot实现集群模式

    整体结构 Redis.config package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org. ...

  4. Redis整合springboot实现哨兵模式

    整体结构 RedisConfig package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org.s ...

  5. Redis整合Springboot实现数据共享

    代码的整体结构 RedisSessionConfig.java package com.cc.springbootredissession.config;import org.springframew ...

  6. Redis整合Springboot(RedisConfig和 RedisUtils)

    文章目录 Springboot 整合Redis 基础分析 测试使用 序列化 RedisConfig RedisUtil Springboot 整合Redis 基础分析 在 Springboot2.x ...

  7. redis安装步骤(单机配置)

    参考链接:https://www.cnblogs.com/it-cen/p/4295984.html # 环境要求 Centos7,gcc编译环境 下面是具体操作记录 下载解压文件 #下载到 /usr ...

  8. docker中启动redis整合Springboot提示错误解决方案

    一.错误提示 服务器运行一段时间后提示: 错误原因:Redis配置为保存RDB快照,但目前无法在磁盘上持久化.可能修改数据集的命令被禁用,因为此实例配置为在RDB快照失败时报告写入期间的错误. 二.解 ...

  9. redis安装到熟练整合springboot(篇幅较长内容详细)

    尚硅谷课程redis学习笔记 1.在linux下安装redis数据库 这篇文章介绍安装 redis介绍: Redis是一个开源的key-value存储系统. 和Memcached类似,它支持存储的va ...

最新文章

  1. android 布局之RelativeLayout(相对布局)
  2. “中文版GPT-3”来了!用64张V100训练了3周
  3. js等待 callback 执行完毕_前端开发,一篇文章让你彻底搞懂,什么是JavaScript执行机制!...
  4. 二分图的匹配问题以及求解算法
  5. ThinkPHP 数据库操作之数据表模型和基础模型 ( Model )
  6. IllegalThreadStateException
  7. java 追加写入txt文件_ava如何追加写入txt文件
  8. 因变量 方差膨胀系数_请问如何计算潜变量的方差膨胀因子(VIF)?
  9. android 键盘点击事件监听事件,Android 键盘事件触发以及监听
  10. nexus批量更新jar包
  11. sql server 视图_SQL Server –具有引用视图的开发实践
  12. 如何在 Laravel 中 “规范” 的开发验证码发送功能
  13. Linux-shell编程_xargs命令详解
  14. 由于没有远程桌面授权服务器可以提供许可证,远程会话被中断。
  15. 此计算机不支持动态磁盘,磁盘无法分区提示此操作系统不支持动态磁盘故障原因分析与解决...
  16. 算法(一)时间复杂度
  17. Texstudio安装后闪退|重装系统Windows10|texstudio2022
  18. maskrcnn训练问题报错:selected_polygons.append(self.polygons[i]) IndexError: list index out of range
  19. 蘑菇街php面试,蘑菇街面试
  20. 关于windows系统中txt文档的换行符\r\n

热门文章

  1. mysql存储引擎的区别_Mysql的两种存储引擎以及区别
  2. pp助手苹果版_再见!PP助手iOS端即将下线 曾是中国最大的苹果助手
  3. Sharepoint学习笔记—Site Definition系列-- 1、创建Site Columns
  4. UWP 使用OneDrive云存储2.x api(一)【全网首发】
  5. 【转】aspx,ascx和ashx使用小结
  6. WebStrom里设置angular提示,可以在html中提示ts文件的内容
  7. 【JS 逆向百例】复杂的登录过程,最新微博登录逆向
  8. 【CodeForces - 1199C】MP3(思维,离散化)
  9. 【牛客 - 317D】小a与黄金街道(数论,tricks)
  10. 【CodeForces - 1084C】The Fair Nut and String(思维,组合数学)