Redis(二)Springboot注解整合Redis,搭建学习环境

一、概述

本文是基于: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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫985

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值