在新版本的开发过程中项目中用到Redis,所以趁着最近学习下Rdis的使用方法,项目代码已经上传,码云地址:https://gitee.com/dcxgit/springboot_practice/releases
1.0.2版本
首先搭建基础的SpringBoot代码并引入相关jar包这里不做介绍,主要介绍Redis,
项目结构:
引入jar包
<!-- 整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
application.properties配置信息
设置端口号
server.port=8099
#配置数据库连接信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/studentdorm?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.cache.ehcache.cofnig=ehcache.xml
#扫描mapper.xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
#显示sql语句
logging.level.com.dcx.dao=debug
#-------------------------------Redis--------------------------------
spring.redis.host=localhost
spring.redis.port=6379
#根据需要
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
redis中的配置信息
/**
* @Title: RedisConfig.java
* @Package com.dcx.comm.redis
* @Description: TODO
* @author : cxding
* @date 2019年4月18日 下午1:49:56
* @version V1.0
*/
package com.dcx.comm.redis;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
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.StringRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import redis.clients.jedis.JedisPoolConfig;
/**
* @ClassName: RedisConfig
* @Description: TODO
* @author : cxding
* @date 2019年4月18日 下午1:49:56
* @version 1.0
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
/**
* 1.创建JedisPoolConfig对象。在该对象中完成一些链接池配置
*
* @ConfigurationProperties:会将前缀相同的当做一个JedisPoolConfig实体,里面的作为属性
*
*/
@Bean
@ConfigurationProperties(prefix = "spring.redis.lettuce.pool")
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
/**
* 2.创建JedisConnectionFactory:配置redis链接信息
*/
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config) {
JedisConnectionFactory factory = new JedisConnectionFactory();
return factory;
}
/**
* 3.创建RedisTemplate:用于执行Redis操作的方法
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用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);
template.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
/**
*
* @Title: simpleKeyGenerator
* @author: cxding
* @createTime: 2019年4月23日 下午3:11:48
* @return KeyGenerator
*/
@Bean
public KeyGenerator simpleKeyGenerator() {
return (o, method, objects) -> {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getSimpleName());
stringBuilder.append(".");
stringBuilder.append(method.getName());
stringBuilder.append("[");
for (Object obj : objects) {
stringBuilder.append(obj.toString());
}
stringBuilder.append("]");
return stringBuilder.toString();
};
}
/**
* redis缓存配置
* @Title: cacheManager
* @author: cxding
* @createTime: 2019年4月23日 下午3:12:01
* @param redisConnectionFactory
* @return CacheManager
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(600), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
// 为缓存使用
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//这里如果只是几个固定的方法可以在这里写定参数,------------------另一个功能设置不同失效时间,当数据量大的时候防止缓存雪崩
//redisCacheConfigurationMap.put("stu", this.getRedisCacheConfigurationWithTtl(30));
// redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000));
return redisCacheConfigurationMap;
}
// 为缓存使用
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> 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);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}
同时启动类上加上注解
并且在service实现层
加上Cacheable注解
启动redis服务,我采用的是window的版本的安装redis,可参考我的上一篇博客
运行swagger-ui界面
查询出的数据
调用根据id查询学生信息的方法,此时控制台打印出信息sql语句
说明是从数据库中查询的,再看看redis中是否缓存了数据
缓存中的数据与查询出来的一致说明缓存成功。
当我再次从页面点击查询时候,
控制台没有打印出sql语句,说明没有从数据库中查询数据