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. IDEA 操作及快捷键总结

    一.设置IDEA使用Eclipse快捷键 File->Settings->Keymap->选择Eclipse,就可以使用Eclipse的快捷键了,但是不能修改.如果想要修改,需要点击 ...

  2. notepad编写html

    notepad写代码的过程: 1.打开notepad,新建一个文档,然后保存,文件的后缀名为.html,代码保存前界面上文件名称为红色,保存后蓝色: 2.保存为html后,进行代码的输入,如果设置好自 ...

  3. 一个本科学生对Linux的认知

    我是一名大三的普通一本大学的软件工程的一名学生,学校开设了一些关于系统开发的课程,纸上得来终觉浅,学校的课程课时较短,想要在56个课时之内学会一些公司需要的技能,无疑是纸上谈兵,一门语言的学习,需要的 ...

  4. Codeforces Round #416 (Div. 2) B. Vladik and Complicated Book

    B. Vladik and Complicated Book time limit per test 2 seconds memory limit per test 256 megabytes inp ...

  5. Migrate Maven Projects to Java 11

    Migrate Maven Projects to Java 11 So you want to migrate to Java 11 but your Maven project is still ...

  6. CQOI2009叶子的染色

    叶子的染色 题目描述 给一棵m个结点的无根树,你可以选择一个度数大于1的结点作为根,然后给一些结点(根.内部结点和叶子均可)着以黑色或白色.你的着色方案应该保证根结点到每个叶子的简单路径上都至少包含一 ...

  7. HNOI2017礼物

    礼物 这估计是最水,最无脑的一道题了 首先发现总和最接近时答案最小 发现答案就是\((\sum_{i=1}^{n}a[i]^2+b[i]^2)-2*max(\sum_{i=1}^{n}a[i]*b[i ...

  8. NOIP2018退役记

    退役失败*1. md可能只有一次啊.

  9. 博主自传——蒟蒻的OI之路

    博主来自河北石家庄市第二中学,现在读高二,主攻信息学竞赛(其实并没有学习其他学科竞赛). NOIP中人品大爆发,使劲挤进河北省一等奖队伍,侥幸留在竞赛团队中(差点就淘汰出局啦). 关于我的ID,YOU ...

  10. 【转】用emWin进度条控件做个表盘控件,效果不错

    @2018-08-09 用emWin进度条控件做个表盘控件,效果不错