引入依赖:
<!-- <commons-pool2.version>2.6.1</commons-pool2.version> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons-pool2.version}</version>
</dependency>
增加配置 (根据自己的情况配置)
spring:
#单个redis配置
redis:
#Redis服务器地址
host: 127.0.0.1
#Redis服务器连接端口
port: 6379
#Redis服务器连接密码(默认为空)
password:
# Redis数据库索引(默认为0)
database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 32
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
# 连接超时时间(毫秒)
timeout: 0
如果你的redis有密码,配置下即可。经过上述两步的操作,你可以访问redis数据了。
但是,还需要一些简单的配置。 比如序列化redisTemplete保存的数据呀,还有就是redis缓存的配置
package com.springboot.main.core.config.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @method redis配置: RedisConfig文件名不能修改 ; 配置序列化方式以及缓存管理器 @EnableCaching 开启缓存
* @author Mr yi
* @time 2019年5月6日
*/
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
/**
* @method 配置自定义redisTemplate;
* 因为使用的连接客户端为:Lettuce,所以RedisConnectionFactory实际传入数据为
* LettuceConnectionFactory
* @author Mr yi
* @time 2019年5月6日
* @param connectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setValueSerializer(jackson2JsonRedisSerializer());
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
/**
* @method json序列化
* @author Mr yi
* @time 2019年5月6日
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
/**
* @method 配置缓存管理器 ; 需要注意的是 你在RedisTemplate<String,
* Object>中的配置的key,value序列化方法并不会生效; 需要在RedisCacheConfiguration中单独配置。
* @author Mr yi
* @time 2019年5月6日
* @param redisConnectionFactory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 生成一个默认配置,通过config对象即可对缓存进行自定义配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 设置缓存的默认过期时间,也是使用Duration设置 (此处为缓存1分钟)
config = config.entryTtl(Duration.ofMinutes(1))
// 设置 key为string序列化
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
// 设置value为json序列化
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
// 不缓存空值
.disableCachingNullValues();
// 设置一个初始化的缓存空间set集合
Set<String> cacheNames = new HashSet<>();
cacheNames.add("timeGroup");
cacheNames.add("user");
cacheNames.add("UUser");
// 对每个缓存空间应用不同的配置
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("timeGroup", config);
// 该缓存空间,缓存时间120秒
configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));
configMap.put("UUser", config.entryTtl(Duration.ofDays(3)));
// 使用自定义的缓存配置初始化一个cacheManager
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
// 一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
.initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();
return cacheManager;
}
}
redis的保存数据调用的例子:
@Controller
@Slf4j
@RequestMapping("/test")
public class TestController {
@Autowired
private RedisTemplate redisTemplate;
/**
* redis 的测试方法(添加、获取、删除)
* @return
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
@RequestMapping("/getReids")
public String getReids() throws InterruptedException {
Test user=new Test( );
user.setId(1).setName("Mr yi").setAge(10);
redisTemplate.opsForValue().set("uUserTest", user);
Object uu = redisTemplate.opsForValue().get("uUserTest");
redisTemplate.delete("uUserTest");
log.info("redis中获取数据:[{}]", uu);
return uu.toString();
}
}
使用redis缓存的例子:
package com.toad.swan.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.toad.swan.entity.UUser;
import com.toad.swan.mapper.UUserMapper;
import com.toad.swan.service.UUserService;
import com.toad.swan.web.param.UUserParam;
import com.toad.swan.web.vo.UUserVo;
import com.toad.common.baseclass.*;
import com.toad.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
/**
* <p>
* 服务实现类
* </p>
*
* @author wangqinmin
* @since 2019-03-21
*/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UUserServiceImpl extends BaseServiceImpl<UUserMapper, UUser> implements UUserService {
@Autowired
private UUserMapper uUserMapper;
/**
* 修改缓存
* <p>
* redis缓存--更新(修改)数据
*
* @param uUser
* @return
* @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存
*/
@CachePut(value = {"user"}, key = "#root.args[0]", unless = "#user eq null ")
@Override
public boolean redisCacheUpdateById(UUser uUser) {
int i = uUserMapper.updateById(uUser);
if (i == 1) {
return true;
}
return false;
}
/**
* 删除缓存
*
* @param id
* @return
* @CacheEvict 应用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据condition 与unless相反,只有表达式为真才会执行。
* redis缓存--移除数据
*/
@CacheEvict(value = {"user"}, key = "#root.args[0]", condition = "#result eq true")
@Override
public boolean redisCacheRemoveById(String id) {
int i = uUserMapper.deleteById(id);
if (i == 1) {
return true;
}
return false;
}
/**
* redis缓存--获取一条数据
*
* @param id
* @return
* @Cacheable 应用到读取数据的方法上,先从缓存中读取,如果没有再从DB获取数据,然后把数据添加到缓存中key 缓存在redis中的keyunless 表示条件表达式成立的话不放入缓存
*/
@Cacheable(value = "user", key = "args[0]", unless = "#result eq null ")
@Override
public UUserVo redisCacheGetUUserById(String id) {
return uUserMapper.getUUserById(id);
}
}
如果你觉得本篇文章对你有所帮助的话,麻烦请点击头像右边的关注按钮,谢谢!
技术在交流中进步,知识在分享中传播