redis安装

参考:https://www.cnblogs.com/LQBlog/p/9214517.html

单机版

1.添加pom依赖

<!-- Spring Boot Reids 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>1.5.7.RELEASE</version></dependency><!--spring2.0集成redis所需common-pool2--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency>

2.application.properties配置redis连接信息

springredis:host: 192.168.65.128port: 6379timeout: 0password: # 密码 没有则不填

3.添加测试代码

@Service
public class AddressServiceImpl extends BaseServiceImpl<Address> implements AddressService {@ResourceAddressMapper addressMapper;@Autowiredprivate RedisTemplate<Object,Object> redisTemplate;@Overridepublic Address selectByPrimaryKey(Object key) {String redisKey=key.toString();Address address=(Address) redisTemplate.opsForValue().get(redisKey);if(address==null){//防止缓存穿透synchronized (this) {address = (Address) redisTemplate.opsForValue().get(redisKey);if (address == null) {address = super.selectByPrimaryKey(key);redisTemplate.opsForValue().set(redisKey, address);}}}else {System.out.println("使用缓存了");}return address;}
}

红色代码是为了防止内存穿透,比如你这个业务方法有10000个人同时访问,如果不加锁。当第一次访问都判断address为空 然后全部去查数据库,正常应该是一个连接查询数据库并设置缓存 后面9999都使用缓存

通过redis Desktop Manager查看结果

因默认key 和value都是用jdk自带的序列化方式JdkSerializationRedisSerializer 可以发现可读性很差

自定义序列化方式

新增一个redisConfig 配置序列化方式

@Configuration
public class RedisConfig {/*** redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类* @param redisConnectionFactory* @return*/@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);// 使用Jackson2JsonRedisSerialize 替换默认序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);// 设置value的序列化规则和 key的序列化规则redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}
}

再次测试结果

集群版

1.application.properties配置

  redis:cluster:master: myMasternodes: 192.168.65.128:6379,192.168.65.128:6380,192.168.65.128:6381,192.168.65.128:6382,192.168.65.128:6383,192.168.65.128:6384timeout: 0

2.配置jedisCluster

@Configuration
public class RedisConfig {@Value("${spring.redis.cluster.nodes}")private String clusterNodes;@Value("${spring.redis.timeout}")private int timeout;@Beanpublic JedisCluster getJedisCluster() {String[] cNodes = clusterNodes.split(",");Set<HostAndPort> nodes = new HashSet<HostAndPort>();// 分割出集群节点for (String node : cNodes) {String[] hp = node.split(":");nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1])));}// 创建集群对象
//      JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout);JedisCluster jedisCluster = new JedisCluster(nodes);return jedisCluster;}}

3.缓存操作 都通过jedisCluster来操作

package com.liqiang.utils;import com.fasterxml.jackson.databind.JsonSerializable;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.JedisCluster;
import tk.mybatis.mapper.util.StringUtil;import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.LinkedHashMap;
import java.util.Map;@Component
public class RedisUtil {protected int DEFAULT_EXPIRED_TIME_SECONDS_OBJECT = 1296000;@Autowiredprivate JedisCluster jedisCluster;public boolean putString(String sKey, String sValue, int expiredInSeconds) {boolean result = false;if (StringUtil.isEmpty(sKey)) {return result;}if (this.jedisCluster != null) {this.jedisCluster.set(sKey, sValue);if (expiredInSeconds > 0) {this.jedisCluster.expire(sKey, expiredInSeconds);}result = true;}return result;}public boolean putString(String sKey, String sValue) {return putString(sKey, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);}public String getString(String sKey) {String result = null;if (StringUtil.isEmpty(sKey)) {return result;}if (this.jedisCluster != null) {result = this.jedisCluster.get(sKey);}return result;}public boolean putObject(String sKey, Serializable object, int expiredInSeconds) {boolean result = false;if (StringUtil.isEmpty(sKey)) {return result;}if (this.jedisCluster != null) {byte[] datas = SerializationUtils.serialize(object);byte[] arrKey = sKey.getBytes();this.jedisCluster.set(arrKey, datas);if (expiredInSeconds > 0) {this.jedisCluster.expire(arrKey, expiredInSeconds);}result = true;}return result;}public boolean putObject(String sKey, Serializable object) {return putObject(sKey, object, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);}public <T> T getObject(String sKey, Class<T> oclass) {Object result = null;if (StringUtil.isEmpty(sKey)) {return null;}System.out.println(sKey);if (this.jedisCluster != null) {byte[] arrKey = sKey.getBytes();byte[] datas = this.jedisCluster.get(arrKey);if ((datas != null) && (datas.length > 0)) {result = SerializationUtils.deserialize(datas);}}System.out.println("dddd");System.out.println(result);return (T) result;}public boolean putMap(String sKey, Map<String, String> oMap, int expiredInSeconds) {boolean result = false;if ((StringUtil.isEmpty(sKey)) || (oMap == null) || (oMap.size() <= 0)) {return result;}if (this.jedisCluster != null) {this.jedisCluster.hmset(sKey, oMap);if (expiredInSeconds > 0) {this.jedisCluster.expire(sKey, expiredInSeconds);}result = true;}return result;}public boolean putMap(String sKey, Map<String, String> oMap) {return putMap(sKey, oMap, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);}public boolean putMap(String sKey, String sField, String sValue, int expiredInSeconds) {boolean result = false;if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {return result;}if (this.jedisCluster != null) {this.jedisCluster.hset(sKey, sField, sValue);if (expiredInSeconds > 0) {this.jedisCluster.expire(sKey, expiredInSeconds);}result = true;}return result;}public boolean putMap(String sKey, String sField, String sValue) {return putMap(sKey, sField, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);}public Map<String, String> getMap(String sKey) {Map result = null;if (StringUtil.isEmpty(sKey)) {return result;}if (this.jedisCluster != null) {result = this.jedisCluster.hgetAll(sKey);}return result;}public Map<String, String> getMap(String sKey, String[] fields) {Map result = null;Map mapAll = getMap(sKey);if ((mapAll != null) && (mapAll.size() > 0) && (fields != null) && (fields.length > 0)) {result = new LinkedHashMap();for (String field : fields) {result.put(field, mapAll.get(field));}}return result;}public boolean existsMapItem(String sKey, String sField) {if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {return false;}if (this.jedisCluster != null) {return this.jedisCluster.hexists(sKey, sField).booleanValue();}return false;}public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue, int expiredInSeconds) {boolean result = false;if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {return result;}if (this.jedisCluster != null) {byte[] arrKey = sKey.getBytes();this.jedisCluster.hset(arrKey, sField.getBytes(), SerializationUtils.serialize(oValue));if (expiredInSeconds > 0) {this.jedisCluster.expire(arrKey, expiredInSeconds);}result = true;}return result;}public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue) {return putMapValueAsObject(sKey, sField, oValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);}public <T> T getMapValueAsObject(String sKey, String sField, Class<T> oClass) {Object result = null;if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {return null;}if (this.jedisCluster != null) {byte[] datas = this.jedisCluster.hget(sKey.getBytes(), sField.getBytes());if ((datas != null) && (datas.length > 0)) {Object tmpObject = SerializationUtils.deserialize(datas);result = tmpObject;}}return (T) result;}public void remove(String sKey) {if (StringUtil.isEmpty(sKey)) {return;}if (this.jedisCluster != null)this.jedisCluster.del(sKey);}}

转载于:https://www.cnblogs.com/LQBlog/p/9242750.html

Spring Boot-整合redis(六)相关推荐

  1. Spring boot - 整合 Redis缓存(上)

    一.配置Pom文件 在使用spring boot 2.0整合redis时遇到了好多问题,网上很多例子都是1.x版本的.故2.0没有折腾好所以将2.0降到了1.5.降级后由于thymeleaf版本也会从 ...

  2. Spring Boot基础学习笔记08:Spring Boot整合Redis

    文章目录 零.学习目标 1.熟悉Redis相关概念 2.掌握使用Spring Boot整合Redis 一.Redis概述 1.Redis简介 2.Redis优点 (1)存取速度快 (2)数据类型丰富 ...

  3. 十一、Spring Boot整合Redis(一)

    Spring Boot整合Redis    1. SpringBoot+单例Redis 1)引入依赖 <dependency>     <groupId>org.springf ...

  4. Spring boot整合Redis(入门教程)

    目录 源码分析 jedis VS lettuce 整合测试 导入依赖 配置连接 测试 存入字符串 存入对象 五大数据类型操作 自定义RedisConfig 存入对象 Redis工具类(常用API) 以 ...

  5. 大聪明教你学Java | Spring Boot 整合 Redis 实现访问量统计

    前言 之前开发系统的时候客户提到了一个需求:需要统计某些页面的访问量,记得当时还纠结了一阵子,不知道怎么去实现这个功能,后来还是在大佬的带领下借助 Redis 实现了这个功能.今天又回想起了这件事,正 ...

  6. Spring Boot 整合Redis 包含Java操作Redis哨兵 作者:哇塞大嘴好帥(哇塞大嘴好帅)

    Spring Boot 整合Redis 包含Java操作Redis哨兵 作者:哇塞大嘴好帥(哇塞大嘴好帅) 1. 配置环境 在SpringBoot2.0版本以后,原来使用的jedis被替换成为了let ...

  7. Spring boot整合Redis实现发布订阅(超详细)

    Redis发布订阅 基础知识 相关命令 订阅者/等待接收消息 发布者/发送消息 订阅者/成功接收消息 常用命令汇总 原理 Spring boot整合redis 导入依赖 Redis配置 消息封装类(M ...

  8. 微服务Spring Boot 整合 Redis 实现 好友关注

    文章目录 ⛅引言 一.Redis 实现好友关注 -- 关注与取消关注 二.Redis 实现好友关注 -- 共同关注功能 ⛵小结 ⛅引言 本博文参考 黑马 程序员B站 Redis课程系列 在点评项目中, ...

  9. 猿创征文 | 微服务 Spring Boot 整合Redis 实战开发解决高并发数据缓存

    文章目录 一.什么是 缓存? ⛅为什么用缓存? ⚡如何使用缓存 二.实现一个商家缓存 ⌛环境搭建 ♨️核心源码 ✅测试接口 三.采用 微服务 Spring Boot 注解开启缓存 ✂️@CacheEn ...

  10. [由零开始]Spring boot 整合redis集群

    Spring boot 整合redis集群 一.环境搭建 Redis集群环境搭建:https://blog.csdn.net/qq497811258/article/details/108124697 ...

最新文章

  1. 改进YOLO | 可能这才是用Transformer正确打开YOLO的方式吧?
  2. 《算法笔记》中文版 - 包括数组,链表,树,图,递归,DP,有序表等相关数据结构与算法的讲解及代码实现...
  3. 马斯克现场直播介绍他的脑机接口公司Neuralink最新进展
  4. Windows 08R2 IIS网站架设
  5. 一直都想总结一下自己遇到过的web安全方面的问题--2015-03-31
  6. c++ main函数调用 类中的枚举_为啥用枚举,枚举有哪些用法?
  7. 【ActiveMQ】消息生产者自动注入报错:Could not autowire. No beans of 'JmsMessagingTemplate' type found...
  8. girton college map
  9. 001.Parted工具使用
  10. 5.Vue 计算属性和侦听器
  11. 7.JasperReports学习笔记7-applet打印
  12. python sklearn 绘制决策树模型的节点图
  13. jdbc与java数据库编程_JDBC与JAVA数据库编程
  14. linux科学计算器设计,课内资源 - Linux环境下的多项式计算器的实现
  15. 计算机系徽文案例,信息技术系——系徽征集令,重磅发布!
  16. ADSL路由切换IP
  17. 读掘金小册组件精讲总结3
  18. Ubuntu 18.04 安装无线网卡
  19. 《显微镜下的大明》马伯庸2019年1月新书mobi、epub、PDF资源共享
  20. 无版权素材网站,免费、可商用

热门文章

  1. 32位进位选择加法器_超前进位加法器amp;行波进位加法器
  2. [趣味分享]纯手工机械的无碳小车
  3. python 埋点 库_测试~python库介绍(一) opencv
  4. C语言数据结构应用(图书借阅系统)
  5. win10安装sql server2000卡住在“安装程序正在安装 Microsoft 数据访问组件 (MDAC)...
  6. 用数据线连接电脑是电脑会对手机强行充电会对电池产生影响
  7. 银行卡信息验证API接口调用接入流程
  8. [附源码]JAVA+ssm计算机毕业设计安庆师范大学校园互助平台(程序+Lw)
  9. 华为手机_text是什么文件_text函数怎么使用
  10. linux flash模块分层