1. springboot和用redis做缓存的整合
这里要整合的是springboot2.x和redis,所以你要把你的springboot 版本在开始之前换成springboot2.0之后的
具体怎么换其实就是换一下版本号,不换的话后面会有很多问题,楼主踩了无数坑
项目地址 https://github.com/HouChenggong/springboot_redis_cache.git
1.1 换版本号
//就是把version换成2.0以后的
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
1.2 添加maven的依赖
还会用到这个maven依赖,总之先添加上把,后面会有用到的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
1.3 数据库连接添加redis
spring:
redis:
host: 127.0.0.1
port: 6379
database: 2
timeout: 60s # 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
# 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
jedis:
pool:
# 最大空闲连接数
max-idle: 8
# 最小空闲连接数
min-idle: 0
# 等待可用连接的最大时间,负数为不限制
max-wait: -1s
# 最大活跃连接数,负数为不限制
max-active: -1
1.3 然后开启reidis缓存
package com.pf.org.cms;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
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.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.*;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.time.Duration;
@EnableScheduling
@SpringBootApplication
@EnableCaching
public class CmsApplication {
public static void main(String[] args) {
SpringApplication.run(CmsApplication.class, args);
}
}
2. 添加代码实现
2.1 Entity
注意这里实现了序列化
public class MyRedisDO implements Serializable {
private Integer id ;
private String name ;
private String note ;
getter and setter ....
}
2.2 Mapper mapper.xml
import com.pf.org.cms.hcg.system.bean.MyRedisDO;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MyRedisMapper {
int del(Integer id);
int insert(MyRedisDO record);
MyRedisDO selectById(Integer id);
//获取用户id和user_name
List<MyRedisDO> selectAll();
int update(MyRedisDO record);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/myba