spring boot(九):Spring Boot中Redis的使用
Redis实战代码
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.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
3、添加cache的配置类
package cn.cnki.ref.config; import java.lang.reflect.Method; 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.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
@EnableCaching
public class MyRedisConfig extends CachingConfigurerSupport{ @Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} @SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
} @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
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.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
} }
测试
package cn.cnki.ref.config; import cn.cnki.ref.pojo.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class MyRedisConfigTest { @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate redisTemplate; @Test
public void test() throws Exception {
stringRedisTemplate.opsForValue().set("key", "mf");
//Assert.assertEquals("mf", stringRedisTemplate.opsForValue().get("key"));
} @Test
public void testObj() throws Exception {
User user = new User(1, "mf", "沐风", 20, "15010298065", "123456@qq.com");
ValueOperations<String, User> operations = redisTemplate.opsForValue();
operations.set("user", user);
operations.set("userkey", user, 30, TimeUnit.SECONDS);//30秒过期 boolean exists = redisTemplate.hasKey("user");
if (exists) {
System.out.println("exists is true");
} else {
System.out.println("exists is false");
}
//redisTemplate.delete("user");
// Assert.assertEquals("mf", operations.get("user").getUserName());
}
}
自动根据方法生成缓存
@GetMapping("/getUserRedis")
@Cacheable(value="key-Users")
public User getUserRedis() {
User user = new User(1, "mf", "沐风", 20, "15010298065", "123456@qq.com");
System.out.println(user);
return user;
}
RedisTemplate的各种操作
RedisTemplate访问Redis数据结构(一)——String
RedisTemplate访问Redis数据结构(二)——List
RedisTemplate访问Redis数据结构(三)——Hash
RedisTemplate访问Redis数据结构(四)——Set
RedisTemplate访问Redis数据结构(五)——ZSet
关于RedisTemplate和StringRedisTemplate
RedisTemplate看这个类的名字后缀是Template,如果了解过Spring如何连接关系型数据库的,大概不会难猜出这个类是做什么的 ,它跟JdbcTemplate一样封装了对Redis的一些常用的操作,当然 StringRedisTemplate跟RedisTemplate功能类似那么肯定就会有人问,为什么会需要两个Template呢,一个不就够了吗?其实他们两者之间的区别主要在于他们使用的序列化类。
- RedisTemplate使用的是 JdkSerializationRedisSerializer
- StringRedisTemplate使用的是 StringRedisSerializer
Redis分布式锁
https://www.cnblogs.com/toutou/p/redis_lock.html
资料
https://blog.csdn.net/weixin_37490221/article/details/78134521
spring boot(九):Spring Boot中Redis的使用的更多相关文章
- spring学习九 spring aop详解
本文来自于:https://www.cnblogs.com/jingzhishen/p/4980551.html AOP(Aspect-Oriented Programming,面向方面编程),可以说 ...
- Spring学习(九)-----Spring bean配置继承
在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...
- 玩转spring MVC(九)---Spring Data JPA
偷个懒 在网上看有写的比较好的,直接贴个链接吧:http://***/forum/blogPost/list/7000.html 版权声明:本文为博主原创文章,未经博主允许不得转载.
- Spring学习(十一)-----Spring使用@Required注解依赖检查
Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...
- SpringBoot(三) :Spring boot 中 Redis 的使用
前言: 这一篇讲的是Spring Boot中Redis的运用,之前没有在项目中用过Redis,所以没有太大的感觉,以后可能需要回头再来仔细看看. 原文出处: 纯洁的微笑 SpringBoot对常用的数 ...
- Spring Boot WebFlux-07——WebFlux 中 Redis 实现缓存
第07课:WebFlux 中 Redis 实现缓存 前言 首先,补充下上一篇的内容,RedisTemplate 实现操作 Redis,但操作是同步的,不是 Reactive 的.自然,支持 React ...
- Spring Boot (五): Redis缓存使用姿势盘点
1. Redis 简介 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化 ...
- spring boot通过Spring Data Redis集成redis
在spring boot中,默认集成的redis是Spring Data Redis,Spring Data Redis针对redis提供了非常方便的操作模版RedisTemplate idea中新建 ...
- Spring Boot(2)中的yaml配置简介
搞Spring Boot的小伙伴都知道,Spring Boot中的配置文件有两种格式,properties或者yaml,一般情况下,两者可以随意使用,选择自己顺手的就行了,那么这两者完全一样吗?肯定不 ...
- Spring Boot 2.x 缓存应用 Redis注解与非注解方式入门教程
Redis 在 Spring Boot 2.x 中相比 1.5.x 版本,有一些改变.redis 默认链接池,1.5.x 使用了 jedis,而2.x 使用了 lettuce Redis 接入 Spr ...
随机推荐
- number (2)变量相关错误
变量没有被定义 fw cannot be resolved 变量没有被初始化 正确代码 package com.itheima_01; import java.io.FileWriter;import ...
- ionic2中如何使用自动生成器
ionic generator是命令行的功能,ionic2自动帮我们创建应用程序,从而节省了大量的时间,并增加我们的速度来开发一个项目的关键部分. ionic generator使我们可以自动创建以下 ...
- React Native & Web APP
React Native Build native mobile apps using JavaScript and React https://facebook.github.io/react-na ...
- loadrunner报错
Action.c(1516): Error -27727: Step download timeout (120 seconds) has expired when downloading resou ...
- Bootstrap排版——HTML元素的样式重定义
前面的话 Bootstrap对默认的HTML元素进行了CSS样式定义,使得各种基本结构套用出来的HTML页面更加美观.本文将详细介绍Bootstrap中排版相关的内容 标题 [h] HTML 中的所有 ...
- jenkins--svn基本使用
新建项目 源码管理 #选择svn配置 svn基本信息配置 其中包括: Repository URL: svn://10.101.0.XXX:9507/XXXX Credentials: 配置你的 ...
- BZOJ3862Little Devil I——树链剖分+线段树
题目大意: 给一棵树,每条边可能是黑色或白色(起始都是白色),有三种操作: 1.将u到v路径上所有边颜色翻转(黑->白,白->黑) 2.将只有一个点在u到v路径上的边颜色翻转 3.查询u到 ...
- python成长之路五-文件操作
1,文件操作 f = open("D:\种子.txt",encoding="utf-8",mode="r") # 打开一个种子.txt文件, ...
- Android 视频 教程 源码 电子书 网址
资源名称 资源地址 下载量 好评率8天快速掌握Android视频教程67集(附源码)http://down.51cto.com/zt/2197 32157Android开发入门之实战技巧和源码 htt ...
- 【BZOJ1802】[AHOI2009]checker(动态规划)
[BZOJ1802][AHOI2009]checker(动态规划) 题面 BZOJ 洛谷 题解 首先自己观察一波,发现如果有相邻两个格子都是红色的话,那么显然可以在任意位置都存在一个跳棋.可以让两个位 ...