spring boot(九):Spring Boot中Redis的使用

时间:2022-05-20 01:34:25

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());
}
}

spring boot(九):Spring Boot中Redis的使用

自动根据方法生成缓存

 @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