Spring Boot-整合redis(六)
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连接信息
spring
redis:
host: 192.168.65.128
port: 6379
timeout: 0
password: # 密码 没有则不填
3.添加测试代码
@Service
public class AddressServiceImpl extends BaseServiceImpl<Address> implements AddressService {
@Resource
AddressMapper addressMapper; @Autowired
private RedisTemplate<Object,Object> redisTemplate;
@Override
public 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
*/
@Bean
public 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: myMaster
nodes: 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:6384
timeout: 0
2.配置jedisCluster
@Configuration
public class RedisConfig { @Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Value("${spring.redis.timeout}")
private int timeout; @Bean
public 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; @Autowired
private 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);
} }
Spring Boot-整合redis(六)的更多相关文章
- SpringBoot入门系列(七)Spring Boot整合Redis缓存
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...
- Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能
Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能 开篇 现在的网站基本都有邮件注册功能,毕竟可以通过邮件定期的给用户发送一些 垃圾邮件 精选推荐
- Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...
- (转)spring boot整合redis
一篇写的更清晰的文章,包括redis序列化:http://makaidong.com/ncjava/330749_5285125.html 1.项目目录结构 2.引入所需jar包 <!-- Sp ...
- Spring Boot 整合 Redis 实现缓存操作
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 ...
- spring boot整合redis,以及设置缓存过期时间
spring-boot 整合 redis 注:redis服务器要先开启 pom文件: <dependency> <groupId>org.springframework.boo ...
- spring boot 2.x 系列 —— spring boot 整合 redis
文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...
- Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis
经过 Spring Boot 的整合封装与自动化配置,在 Spring Boot 中整合Redis 已经变得非常容易了,开发者只需要引入 Spring Data Redis 依赖,然后简单配下 red ...
- Spring Boot 整合Redis 实现缓存
本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 ...
- spring boot 整合 redis
自己开发环境需要安装 redis 服务,百度一下很多,下面主要说明Springboot 集成 redis 讲解 我的版本 java8 + redis3.0 + springboot 1.5.9. Sp ...
随机推荐
- luogu3119 草鉴定
题目大意 给出一个有向图,问将图中的哪一个边翻转,会使节点1所在的强连通分量内的节点数最多.输出这个节点数. 题解 让我们看看暴力怎么做,即枚举每一条边,将其翻转,然后求节点1所在强连通分量节点数,然 ...
- Spring+Mybatis之登录功能demo
其实工作之后就没有用过Spring+Mybatis的框架了,因为公司有一个自己开发的框架,讲道理,其实这个与Spring+Mybatis整合很是神似.当然性能上还是比不上Spring+Mybatis所 ...
- Autobiography
Autobiography My name is Donggongdechen. I am ** years old. I was born in XuChang, HeNan province, t ...
- django自带权限控制系统的使用和分析
1.django的权限控制相关表及其相互间的关系: django的所有权限信息存放在auth_permission表中,用户user和用户组group都可以有对应的权限permission.分别存放在 ...
- 希尔shell排序——java实现
希尔排序是对插入排序的优化,将插入排序的交换步长由1增加到h. 希尔排序的思想是使数组中任意间隔为h的元素有序.步长调幅为h = 3*h + 1, 也就是1,4,13,40,121,364, 1003 ...
- Squares(枚举+set 查找)
http://poj.org/problem?id=2002 题意:给出n组坐标,判断这些坐标能组成的正方形的个数. 思路:参考某大神的想法,先枚举两个点,然后利用公式表示出另外两个点,判断这两个点是 ...
- 0420-mysql命令(数据库操作层级,建表,对表的操作)
注意事项: 符号必须为英文. 数据库操作层级: 建表大全: #新建表zuoye1:drop table if exists zuoye1;create table zuoye1( id int ...
- idea使用svn
一.在idea中配置svn 二.导出maven项目 连接svn 点击checkout 点击ok就可以 到Commit Changes 这里有几个选项需要了解的: Auto-update after c ...
- [转]逐步解說:在 WPF 應用程式中使用 ReportViewer 显示 rdlc
本文转自:http://msdn.microsoft.com/zh-tw/library/hh273267 若要在 WPF 應用程式中使用 ReportViewer 控制項,您需要將 ReportVi ...
- BZOJ 2333 左偏树 (写得我人生都崩溃了...)
思路: 高一神犇 竟然 问我这道题 我光荣地 看着题解(划掉) 写了一下午 QaQ multiset不能erase(一个值) 这样就把等于这个值 的数都erase掉了 (woc我一开始不 ...