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的使用的更多相关文章

  1. spring学习九 spring aop详解

    本文来自于:https://www.cnblogs.com/jingzhishen/p/4980551.html AOP(Aspect-Oriented Programming,面向方面编程),可以说 ...

  2. Spring学习(九)-----Spring bean配置继承

    在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...

  3. 玩转spring MVC(九)---Spring Data JPA

    偷个懒 在网上看有写的比较好的,直接贴个链接吧:http://***/forum/blogPost/list/7000.html 版权声明:本文为博主原创文章,未经博主允许不得转载.

  4. Spring学习(十一)-----Spring使用@Required注解依赖检查

    Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...

  5. SpringBoot(三) :Spring boot 中 Redis 的使用

    前言: 这一篇讲的是Spring Boot中Redis的运用,之前没有在项目中用过Redis,所以没有太大的感觉,以后可能需要回头再来仔细看看. 原文出处: 纯洁的微笑 SpringBoot对常用的数 ...

  6. Spring Boot WebFlux-07——WebFlux 中 Redis 实现缓存

    第07课:WebFlux 中 Redis 实现缓存 前言 首先,补充下上一篇的内容,RedisTemplate 实现操作 Redis,但操作是同步的,不是 Reactive 的.自然,支持 React ...

  7. Spring Boot (五): Redis缓存使用姿势盘点

    1. Redis 简介 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化 ...

  8. spring boot通过Spring Data Redis集成redis

    在spring boot中,默认集成的redis是Spring Data Redis,Spring Data Redis针对redis提供了非常方便的操作模版RedisTemplate idea中新建 ...

  9. Spring Boot(2)中的yaml配置简介

    搞Spring Boot的小伙伴都知道,Spring Boot中的配置文件有两种格式,properties或者yaml,一般情况下,两者可以随意使用,选择自己顺手的就行了,那么这两者完全一样吗?肯定不 ...

  10. Spring Boot 2.x 缓存应用 Redis注解与非注解方式入门教程

    Redis 在 Spring Boot 2.x 中相比 1.5.x 版本,有一些改变.redis 默认链接池,1.5.x 使用了 jedis,而2.x 使用了 lettuce Redis 接入 Spr ...

随机推荐

  1. [转帖] select、poll、epoll之间的区别总结[整理] + 知乎大神解答 https://blog.csdn.net/qq546770908/article/details/53082870 不过图都裂了.

    select.poll.epoll之间的区别总结[整理] + 知乎大神解答 2016年11月08日 15:37:15 阅读数:2569 http://www.cnblogs.com/Anker/p/3 ...

  2. 理解 Delphi 的类(十) - 深入方法[17] - 提前声明

    //要点17: 如果前面的方法要调用后面的方法, 后面的方法需要提前声明 function MyFunB(x: Integer): Integer; forward; {使用 forward 指示字提 ...

  3. BZOJ2178 圆的面积并(simpson积分)

    板子题.可以转一下坐标防止被卡.精度和常数实在难以平衡. #include<iostream> #include<cstdio> #include<cmath> # ...

  4. EF code first 迁移问题

    错误 : 支持"Entities"上下文的模型已在数据库创建后发生更改.请考虑使用 Code First 迁移更新数据库(http://go.microsoft.com/fwlin ...

  5. BAI度 内部资料!Python_Threads多线程

    基本介绍 runable运行sleeping等待dead销毁(run方法执行完成或执行时抛出异常) 类继承threading.Thread线程的状态 函数介绍 在__init__里调用threadin ...

  6. 机器学习工作流程第一步:如何用Python做数据准备?

    这篇的内容是一系列针对在Python中从零开始运用机器学习能力工作流的辅导第一部分,覆盖了从小组开始的算法编程和其他相关工具.最终会成为一套手工制成的机器语言工作包.这次的内容会首先从数据准备开始. ...

  7. 洛谷 P2341 [HAOI2006]受欢迎的牛 解题报告

    P2341 [HAOI2006]受欢迎的牛 题目描述 每头奶牛都梦想成为牛棚里的明星.被所有奶牛喜欢的奶牛就是一头明星奶牛.所有奶 牛都是自恋狂,每头奶牛总是喜欢自己的.奶牛之间的"喜欢&q ...

  8. 使用netty编写IM通信界面

    前驱知识 WebSocket 维基百科: WebSocket是一种在单个TCP连接上进行全双工通信的协议.WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补 ...

  9. 洛谷P4043 支线剧情

    题意:给定DAG,通过每条边需要时间. 从某号点回到1号点不需要时间. 从1号点出发,求最少要多久才能走完所有边. 解: 有源汇有上下界最小费用可行流. 直接连边,费用为时间,下界为1,无上界. 每个 ...

  10. 洛谷P5163 WD与地图

    只有洛谷的毒瘤才会在毒瘤月赛里出毒瘤题...... 题意:三个操作,删边,改变点权,求点x所在强连通分量内前k大点权之和. 解:狗屎毒瘤数据结构乱堆...... 整体二分套(tarjan+并查集) + ...