springboot如何開(kāi)啟緩存@EnableCaching(使用redis)
更新時(shí)間:2024年11月07日 16:19:10 作者:阿勝yss
在Spring Boot項(xiàng)目中集成Redis主要包括添加依賴到pom.xml、配置application.yml中的Redis連接參數(shù)、編寫(xiě)配置類、在啟動(dòng)類上添加@EnableCaching注解以及測(cè)試接口的查詢和緩存驗(yàn)證等步驟,首先,需要在pom.xml中添加spring-boot-starter-data-redis依賴
添加依賴 pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>application.yml 配置redis連參數(shù)
spring:
# redis 配置
redis:
# 地址
host: 127.0.0.1
# 端口,默認(rèn)為6379
port: 6379
# 數(shù)據(jù)庫(kù)索引
database: 2
# 密碼
password:
# 連接超時(shí)時(shí)間
timeout: 10s配置類
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class CacheConfig {
/**
* 最新版,設(shè)置redis緩存過(guò)期時(shí)間
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl( 60) // 默認(rèn)策略,未配置的 key 會(huì)使用這個(gè)
);
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}啟動(dòng)類上 加 @EnableCaching 注解
測(cè)試
1.接口查詢
2. 緩存查詢驗(yàn)證
@ApiOperation(value = "根據(jù)ID獲取詳情",notes = "查詢")
@Cacheable(cacheNames = "testaCache", key = "#id")
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public TestA get(@PathVariable Long id){
log.info("進(jìn)行了mysql查詢");
return testService.getById(id);
} @GetMapping("/get/redis/cache")
@ApiOperation(value="查看redis緩存信息")
public String getRedisCache(){
// 從IOC容器中通過(guò)類型獲取bean
RedisCacheManager redisCacheManager = SpringUtils.getBean(RedisCacheManager.class);
// 從IOC容器中通過(guò)名稱獲取bean
RedisCacheManager redisCacheManager2 = SpringUtils.getBean("cacheManager");
Cache demoCache = redisCacheManager.getCache("testaCache");
log.info(demoCache.get(78, TestA.class)+"");
return demoCache.getName();
}SpringUtils.class
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware
{
/** Spring應(yīng)用上下文環(huán)境 */
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringUtils.applicationContext = applicationContext;
}
/**
* 獲取對(duì)象
*
* @param name
* @return Object 一個(gè)以所給名字注冊(cè)的bean的實(shí)例
* @throws BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 獲取類型為requiredType的對(duì)象
*
* @param clz
* @return
* @throws BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一個(gè)與所給名稱匹配的bean定義,則返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判斷以給定名字注冊(cè)的bean定義是一個(gè)singleton還是一個(gè)prototype。 如果與給定名字相應(yīng)的bean定義沒(méi)有被找到,將會(huì)拋出一個(gè)異常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注冊(cè)對(duì)象的類型
* @throws NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果給定的bean名字在bean定義中有別名,則返回這些別名
*
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
/**
* 獲取aop代理對(duì)象
*
* @param invoker
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker)
{
return (T) AopContext.currentProxy();
}
/**
* 獲取當(dāng)前的環(huán)境配置,無(wú)配置返回null
*
* @return 當(dāng)前的環(huán)境配置
*/
public static String[] getActiveProfiles()
{
return applicationContext.getEnvironment().getActiveProfiles();
}
/**
* 獲取配置文件中的值
*
* @param key 配置文件的key
* @return 當(dāng)前的配置文件的值
*
*/
public static String getRequiredProperty(String key)
{
return applicationContext.getEnvironment().getRequiredProperty(key);
}
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)冒泡排序與雙向冒泡排序算法的代碼示例
這篇文章主要介紹了Java實(shí)現(xiàn)冒泡排序與雙向冒泡排序算法的代碼示例,值得一提的是所謂的雙向冒泡排序并不比普通的冒泡排序效率來(lái)得高,注意相應(yīng)的時(shí)間復(fù)雜度,需要的朋友可以參考下2016-04-04
mybatis plus or and 的合并寫(xiě)法實(shí)例
這篇文章主要介紹了mybatis plus or and 的合并寫(xiě)法實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Springmvc基于fastjson實(shí)現(xiàn)導(dǎo)包及配置文件
這篇文章主要介紹了Springmvc基于fastjson實(shí)現(xiàn)導(dǎo)包及配置文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
深層剖析java應(yīng)用開(kāi)發(fā)中MyBayis緩存
這篇文章主要為大家深層剖析java開(kāi)發(fā)中MyBayis緩存,文中講解了Mybatis緩存的分類以及使用的方式,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
Springboot設(shè)置文件上傳大小限制的實(shí)現(xiàn)示例
Spring Boot工程嵌入的tomcat限制了請(qǐng)求的文件大小默認(rèn)為1MB,單次請(qǐng)求的文件的總數(shù)不能大于10Mb,本文主要介紹了Springboot設(shè)置文件上傳大小限制的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-11-11

