一、概述
本文是基于:Springboot+mysql+redis+mybatisPlus,进行搭建的。搭建了一个成功使用了redis进行缓存的demo,可以供以后进行redis的学习。
代码已经上传到仓库:https://gitee.com/wyl_985/study-project.git下的study_redis,可以自行拉取查阅。
下图是缓存效果
二、搭建步骤
下面只记录搭建步骤的核心步骤,具体细节自己看study项目源码
1.创建SpringBoot工程
可以用spring initializr来生成一个干净的Springboot工程。
2.引入依赖
<!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatisplus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- redis starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3.配置application.yml
spring:
# mysql数据库4要素+schema脚本+data脚本
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# 是否执行schema.sql,data.sql
# ALWAYS每次启动项目自动执行, EMBEDDED当使用内存数据库才会执行, NEVER不会执行;
initialization-mode: always # 项目首次启动后,生成数据表后记得改回never
# 表结构
schema: classpath:db/schema-mysql.sql
# 数据
data: classpath:db/data-mysql.sql
url: jdbc:mysql://localhost:3306/study_redis?serverTimezone=GMT&useUnicode=true&characterEncoding=utf8&useSSL=false
username: TODO
password: TODO
# redis的url
redis:
host: localhost
port: 6379
mybatis-plus:
configuration:
# 开启mybatis日志打印
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 开启下划线转驼峰
map-underscore-to-camel-case: true
global-config:
db-config:
# 自定义id生成规则
id-type: ASSIGN_UUID
4.编写RedisConfig,设置序列化、反序列化规则
设置redis的序列化和反序列化的规则(本人是使用fastjson)。具体看RedisConfig、MyFastJsonRedisSerializer这3个类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
/**
* 缓存Redis配置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
private RedisConnectionFactory factory;
/**
* 设置@cacheable 序列化方式
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(){
//fastJson默认也有提供一个redis序列化器,但是在fastjson在1.2.25之后的版本后,反序列化的时候会抛出JSONException: autoType is not support
//FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
MyFastJsonRedisSerializer<Object> serializer = new MyFastJsonRedisSerializer<>(Object.class);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
.entryTtl(Duration.ofDays(30)); // 设置 redis 数据默认过期时间
return configuration;
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 说明:自定义redis序列化方式
*/
public class MyFastJsonRedisSerializer<T> implements RedisSerializer<T> {
static {
// 在反序列化的时候根据@type来返回类型
// 参考博客:https://github.com/alibaba/fastjson/wiki/enable_autotype
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private Class<T> clazz;
public MyFastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
// 在序列化的时候保存类的类型信息
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
}
5.测试
三、下一步要学习的
- @Cacheable会对className::方法[方法参数]进行缓存,那么如果修改、删除、刷新这个缓存呢?
- redisTemplate、jedis、redssion的区别是什么
- @Cacheable是属于springCache包下的,要系统学习下springCache