一、环境准备
1、SpringBoot 2.1.0
2、JDK1.8
3、MySQL8.0.17
4、Redis3.0.504
二、MySQL创建测试表
use springboot;
CREATE TABLE user(
userId INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
userName VARCHAR(255),
password VARCHAR(255),
phone VARCHAR(255)
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
三、代码详情
pom文件引入相关依赖
<!-- JSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Redis 缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- alibaba 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
yml配置文件
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
username: root
password: root
redis:
database: 3 #Redis数据库索引
host: localhost
port: 6379
password:
jedis:
pool:
max-active: 8 #连接池最大连接数(负数表示没有限制)
max-wait: -1 #连接池最大阻塞等待时间(负数表示没有限制)
max-idle: 8 #连接池最大空闲连接
min-idle: 0 #连接池最小空闲连接
timeout: 10000ms #连接池连接超时时间(毫秒)
cache:
type: redis
mybatis:
mapper-locations: classpath:mapper/*.xml
Reids配置类——RedisConfig
/**
* redis 缓存配置
* 修改序列化方式,解决缓存乱码
* @param redisConnectionFactory
* @return
*/
@Bean
@SuppressWarnings("all")
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 配置序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration = config
//Key序列化方式redisSerializer
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
//value序列化方式jackson2JsonRedisSerializer
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
//设置前缀
// .prefixKeysWith("project:")
//设置过期时间
.entryTtl(Duration.ofSeconds(60*60));
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(redisCacheConfiguration)
.build();
return cacheManager;
}
/**
* redisTemplate配置
* @param factory
* @return
*
*
* 自定义RedisTemplate的原因:
* 1、修改泛型方式为<String,Object>,避免繁琐的类型转换
* 2、将value的序列化方式更改为Jackson2JsonRedisSerializer,因为底层的RedisSerializer序列化value时不会带双引号,而使用Jackson2JsonRedisSerializer序列化String类型时会自动添加双引号。
*
*/
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
//指定要序列化的域,ANY是包括public和private的
mapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
//指定序列化输入的类型,类必须是非final类型的,否则会报错
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(mapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//设置key采用String的序列化方式
redisTemplate.setKeySerializer(stringRedisSerializer);
//设置hash的key采用String的序列化方式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
//设置value采用jackson2的序列化方式
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//设置hash的value采用jackson2的序列化方式
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* Key生成策略
* @return
*
* target 类
* method 方法
* params 参数
*/
@Bean
public KeyGenerator cacheKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(method.getName()).append(":").append(DateUtil.getCurrentTime());
return sb.toString();
};
}
Controller
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserService userService;
/**
* Cacheable 缓存注解
* value:缓存分区 必填
* key:设置键 选填
* keyGenerator: 设置键生成规则
*/
@RequestMapping(value="/getAll")
@Cacheable(value="map",keyGenerator="cacheKeyGenerator")
public Map<String, Object> getAll() {
List<User> user = userService.getAll(new User());
Map<String, Object> map = new HashMap<String, Object>();
String token = "adadoiwfoioajslkgnaogobg42142oi3nrfkf";
map.put("user", user);
map.put("toKen", token);
return map;
}
启动项目 测试
访问:http://localhost:8080/getAll
测试结果如下
Redis 测试结果
PostMan测试结果
需要注意的地方:
1、因MySQL版本问题有可能会报错时区错误,解决方案:SpringBoot整合MySQL时区问题
2、在使用缓存时,需要在程序启动类和配置类加上@EnableCaching注解来开启缓存,否则缓存失败。
PS:本文只是个人学习记录,若有写错的地方还请指出, 谢谢。