参考:https://www.cnblogs.com/ityouknow/p/5748830.html

如何使用

1、引入 spring-boot-starter-redis

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

2、添加配置文件

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.jedispassword=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pooljedis.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pooljedis.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pooljedis.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pooljedis.min-idle=0
# 连接超时时间(毫秒)
#timeout: 60s # 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
spring.redis.timeout=60s

3、添加cache的配置类

@Configuration
public class RedisConfig extends CachingConfigurerSupport { @Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer); return template;
} @Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题),过期时间30秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(30))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}

一個比較好的redisConfig配置(建议使用)

package com.goku.demo.config;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
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.RedisSerializationContext; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; /***
* *************************************************************************
* <PRE>
* @ClassName: : RedisConfig
*
* @Description: : 使用 redis 做默认缓存
*
* @Creation Date : 25 Feb 2019 3:54:19 PM
*
* @Author : Sea
*
* </PRE>
**************************************************************************
*/
@SuppressWarnings("all")
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
public KeyGenerator simpleKeyGenerator() {
return (o, method, objects) -> {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getSimpleName());
stringBuilder.append(".");
stringBuilder.append(method.getName());
stringBuilder.append("[");
for (Object obj : objects) {
stringBuilder.append(obj.toString());
}
stringBuilder.append("]"); return stringBuilder.toString();
};
} @Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
} /**
* @how to use eg:
@Cacheable(value = "MIN10", keyGenerator = "simpleKeyGenerator") // 3000秒
@Cacheable(value = "MIN30", keyGenerator = "simpleKeyGenerator") // 18000秒
@Cacheable(value = "MIN60", keyGenerator = "simpleKeyGenerator") // 600秒,未指定的key,使用默认策略
****/
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
redisCacheConfigurationMap.put("MIN10", this.getRedisCacheConfigurationWithTtl());
redisCacheConfigurationMap.put("MIN30", this.getRedisCacheConfigurationWithTtl());
redisCacheConfigurationMap.put("MIN60", this.getRedisCacheConfigurationWithTtl());
return redisCacheConfigurationMap;
} /**
* @param Minute
* @return
*/
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer Minute) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofMinutes(Minute)); return redisCacheConfiguration;
} }

3、好了,接下来就可以直接使用了

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis { @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate redisTemplate; @Test
public void test() throws Exception {
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
} @Test
public void testObj() throws Exception {
User user=new User("aa@126.com", "aa", "aa123456", "aa","123");
ValueOperations<String, User> operations=redisTemplate.opsForValue();
operations.set("com.neox", user);
operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
Thread.sleep(1000);
//redisTemplate.delete("com.neo.f");
boolean exists=redisTemplate.hasKey("com.neo.f");
if(exists){
System.out.println("exists is true");
}else{
System.out.println("exists is false");
}
// Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
}
}

以上都是手动使用的方式,如何在查找数据库的时候自动使用缓存呢,看下面;

4、自动根据方法生成缓存

@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}

其中value的值就是缓存到redis中的key

springboot 整合 redis 共享Session-spring-session-data-redis的更多相关文章

  1. springboot整合三 共享session,集成springsession

    官网介绍 - spring:session:https://docs.spring.io/spring-session/docs/current/reference/html5/ 1. Mave依赖 ...

  2. SpringBoot学习笔记(13)----使用Spring Session+redis实现一个简单的集群

    session集群的解决方案: 1.扩展指定server 利用Servlet容器提供的插件功能,自定义HttpSession的创建和管理策略,并通过配置的方式替换掉默认的策略.缺点:耦合Tomcat/ ...

  3. Spring mvc Data Redis—Pub/Sub(附Web项目源码)

    一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...

  4. 【redis】3.Spring 集成注解 redis 项目配置使用

    spring-data-redis  项目,配合 spring 特性并集成 Jedis 的一些命令和方法. 配置redis继承到spring管理项目,使用注解实现redis缓存功能. 参考:http: ...

  5. 【redis】4.spring boot集成redis,实现数据缓存

    参考地址:https://spring.io/guides/gs/messaging-redis/ ================================================== ...

  6. redis序列化异常------------org.springframework.data.redis.serializer.SerializationException

    异常信息; org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested e ...

  7. springboot+spring session+redis+nginx实现session共享和负载均衡

    环境 centos7. jdk1.8.nginx.redis.springboot 1.5.8.RELEASE session共享 添加spring session和redis依赖 <depen ...

  8. Nginx+Tomcat搭建集群,Spring Session+Redis实现Session共享

    小伙伴们好久不见!最近略忙,博客写的有点少,嗯,要加把劲.OK,今天给大家带来一个JavaWeb中常用的架构搭建,即Nginx+Tomcat搭建服务集群,然后通过Spring Session+Redi ...

  9. 【Spring Session】和 Redis 结合实现 Session 共享

    [Spring Session]和 Redis 结合实现 Session 共享 参考官方文档 HttpSession with Redis Guide https://docs.spring.io/s ...

  10. (十九)SpringBoot之使用Spring Session集群-redis

    一.引入maven依赖 <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEnc ...

随机推荐

  1. vscode修改code runner插件默认使用的编译器

    code runner的原理就是自动帮你完成在控制台中输入切换路径和编译源代码以及运行编译好的程序的指令 编译指令是根据配置文件中一开始写好的模板来执行的 不同语言对应一条指令,运行code runn ...

  2. 流媒体技术笔记(DarwinStreamingServer相关)

    简介 Darwin Streaming Server简称DSS.DSS是Apple公司提供的开源实时流媒体播放服务器程序.整个程序使用C++编写,在设计上遵循高性能,简单,模块化等程序设计原则,务求做 ...

  3. mysql查询优化之四:优化特定类型的查询

    本文将介绍如何优化特定类型的查询. 1.优化count()查询count()聚合函数,以及如何优化使用了该函数的查询,很可能是mysql中最容易被误解的前10个话题之一 count() 是一个特殊的函 ...

  4. R语言——实验5-聚类分析

    针对课件中的例子自己实现k-means算法 调用R语言自带kmeans()对给定数据集表示的文档进行聚类. 给定数据集: a)         数据代表的是文本信息. b)        第一行代表词 ...

  5. 廖雪峰Java3异常处理-1错误处理-4自定义异常

    JDK已有的异常: RuntimeException * NullPointerException * IndexOutOfBoundsException * SecurityException * ...

  6. 集合之map详解(遍历)

    13.简单介绍Map 12.Map排序(TreeMap的key排序,TreeMap的value排序:HashMap的value排序:) 11.map集合的6种遍历方式  ============= 2 ...

  7. Kowala协议:一组分布式,自我调节,资产跟踪特性的加密货币(二)

    对于稳定币来言,设计过程中会遇到很多细节的问题,今天来讲述下有关通证设计过程中的一些问题. 1.计算手续费 计算费是交易费的一部分,转移给kUSD矿工,并由以下公式决定: 其gasUsed(t) 是用 ...

  8. [UE4]声音系统概述

    一.只能使用wav格式的声音 二.wav声音可以直接播放到打开的UE4编辑器内打开的Content文件夹.也可以直接导入 三.在Content中的文件夹的声音资源可以直接拖放到场景中,会以3D场景声音 ...

  9. 逻辑运算符&逻辑短路

    (1)and 逻辑与 全真则真,一假则假 print(True and True) #True print(False and True) #False print(False and False) ...

  10. css3凹角效果

    <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Conten ...