spring boot 整合redis实现spring的缓存框架
教程分享
>
Java教程
>
Spring
(30283)
2024-08-07 11:05:25
spring boot 整合redis实现spring的缓存框架
1.创建一个spring boot项目
2.配置pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.leftso</groupId>
<artifactId>demo-springboot-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-springboot-redis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.在spring boot的application配置文件中配置redis的相关信息
####################Redis 配置信息 ##########################
# Redis数据库分片索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=10.1.1.134
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
4.配置redis整合入spring的缓存框架
package com.leftso.config;
import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
@EnableCaching // 继承CachingConfigurerSupport并重写方法,配合该注解实现spring缓存框架的启用
public class RedisConfig extends CachingConfigurerSupport {
/** 载入通过配置文件配置的连接工场 **/
@Autowired
RedisConnectionFactory redisConnectionFactory;
@SuppressWarnings("rawtypes")
@Autowired
RedisTemplate redisTemplate;
@Bean
RedisTemplate<String, Object> objRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
/*
* (non-Javadoc)
*
* @see org.springframework.cache.annotation.CachingConfigurerSupport#
* cacheManager()
*/
@Bean // 必须添加此注解
@Override
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
// redisCacheManager.setDefaultExpiration(60);//秒
return redisCacheManager;
}
/**
* 重写缓存的key生成策略,可根据自身业务需要进行自己的配置生成条件
*
* @see org.springframework.cache.annotation.CachingConfigurerSupport#
* keyGenerator()
*/
@Bean // 必须项
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
5.创建一个测试的pojo和一个测试的controller
package com.leftso.pojo;
import java.io.Serializable;
/**
*
* <pre>
* [Summary]
* 测试用简单类型
* [Detail]
* TODO
* [Author]
* XQLEE
* [Version]
* v1.0
* 2017年5月8日上午9:58:42
* </pre>
*/
public class Address implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String city;
private String detail;
public Address() {
}
public Address(String id, String city, String detail) {
super();
this.id = id;
this.city = city;
this.detail = detail;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city
* the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the detail
*/
public String getDetail() {
return detail;
}
/**
* @param detail
* the detail to set
*/
public void setDetail(String detail) {
this.detail = detail;
}
}
package com.leftso.controller;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.leftso.pojo.Address;
@RestController
public class CacheTestCtrl {
@GetMapping("/getAddr")
@Cacheable(value = "address-cache") // 设置缓存的名称,也可以通过key属性指定缓存的key,keyGenerator指定key生成策略器(keyGenerator一般推荐在重写CachingConfigurerSupport类里面的方法适合全局指定)
public Address getAddress() {
Address addr = new Address("001", "重庆市", "渝北区");
System.out.println("==========你看见这句话表示没有缓存时候打印出来的========");
return addr;
}
}
6.启动spring boot项目,访问地址localhost:8080/getAddr
第一次访问将会在控制台中看到以下输出:
后面多次刷新都不会进入到该方法中去读取信息,而是通过缓存直接读取了缓存信息。
至此spring boot整合redis 实现基本的缓存已经完成。
https://www.leftso.com/article/175.html