javascript
SpringCache与Redis
文章目錄
- SpringCache簡介
- 常?注解Cacheable
- 自定義CacheManager配置和過期時間
- 自定義緩存KeyGenerator
- 常用注解CachePut 和 CacheEvict
- 多注解組合Caching
SpringCache簡介
?檔:https://spring.io/guides/gs/caching/
?Spring 3.1起,提供了類似于@Transactional注解事務的注解Cache?持,且提供了Cache抽象提供基本的Cache抽象,?便切換各種底層Cache只需要更少的代碼就可以完成業務數據的緩存提供事務回滾時也?動回滾緩存,?持?較復雜的緩存邏輯
核?
?個是Cache接?,緩存操作的API
?個是CacheManager管理各類緩存,有多個緩存
項?中引?starter依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId> </dependency>配置?件指定緩存類型
spring:cache:type: redis啟動類開啟緩存注解
@EnableCaching常?注解Cacheable
標記在?個?法上,也可以標記在?個類上緩存標注對象的返回結果,標注在?法上緩存該?法的返回值,標注在類上緩存該類所有的?法返回值value 緩存名稱,可以有多個key 緩存的key規則,可以?springEL表達式,默認是?法參數組合
condition 緩存條件,使?springEL編寫,返回true才緩存
自定義CacheManager配置和過期時間
默認為@Primary注解所標注的CacheManager
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.util.StringUtils;import java.lang.reflect.Method; import java.time.Duration;@Configuration public class AppConfiguration {/*** 新的分頁插件*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}/*** 1分鐘過期** @param connectionFactory* @return*/@Beanpublic RedisCacheManager cacheManager1Minute(RedisConnectionFactory connectionFactory) {RedisCacheConfiguration config = instanceConfig(60L);return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();}/*** 默認是1小時** @param connectionFactory* @return*/@Bean@Primarypublic RedisCacheManager cacheManager1Hour(RedisConnectionFactory connectionFactory) {RedisCacheConfiguration config = instanceConfig(3600L);return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();}/*** 1天過期** @param connectionFactory* @return*/@Beanpublic RedisCacheManager cacheManager1Day(RedisConnectionFactory connectionFactory) {RedisCacheConfiguration config = instanceConfig(3600 * 24L);return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();}private RedisCacheConfiguration instanceConfig(Long ttl) {Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);objectMapper.registerModule(new JavaTimeModule());// 去掉各種@JsonSerialize注解的解析objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);// 只針對非空的值進行序列化objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);// 將類型序列化到屬性json字符串中objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl))//.disableCachingNullValues().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));}}自定義緩存KeyGenerator
@Configuration public class AppConfiguration {/*** 自定義緩存key規則* @return*/@Beanpublic KeyGenerator springCacheCustomKeyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... objects) {String key = o.getClass().getSimpleName() + "_" + method.getName() + "_" + StringUtils.arrayToDelimitedString(objects, "_");System.out.println(key);return key;}};}}key 屬性和keyGenerator屬性只能?選?
CacheManager和keyGenerator使用
@Service public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductMapper productMapper;@Override@Cacheable(value = {"product"}, keyGenerator = "springCacheCustomKeyGenerator",cacheManager = "cacheManager1Minute")public ProductDO findById(int id) {return productMapper.selectById(id);}@Override@Cacheable(value = {"product_page"},keyGenerator = "springCacheCustomKeyGenerator")public Map<String, Object> page(int page, int size) {Page pageInfo = new Page<>(page,size);IPage<ProductDO> iPage = productMapper.selectPage(pageInfo,null);Map<String,Object> pageMap = new HashMap<>(3);pageMap.put("total_record",iPage.getTotal());pageMap.put("total_page",iPage.getPages());pageMap.put("current_data",iPage.getRecords());return pageMap;}}常用注解CachePut 和 CacheEvict
CachePut
根據方法的請求參數對其結果進行緩存,每次都會觸發真實?法的調?value 緩存名稱,可以有多個key 緩存的key規則,可以?springEL表達式,默認是?法參數組合condition 緩存條件,使?springEL編寫,返回true才緩存
CacheEvict
從緩存中移除相應數據, 觸發緩存刪除的操作value 緩存名稱,可以有多個@CachePut(value = {“product”},key =
“#productDO.id”)key 緩存的key規則,可以?springEL表達式,默認是?法參數組合
beforeInvocation = false
緩存的清除是否在?法之前執? ,默認代表緩存清除操作是在?法執?之后執?,如果出現異常緩存就不會清除
beforeInvocation = true
代表清除緩存操作是在?法運?之前執?,?論?法是否出現異常,緩存都清除
多注解組合Caching
組合多個Cache注解使?,允許在同??法上使?多個嵌套的@Cacheable、@CachePut和@CacheEvict注釋
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import net.xdclass.xdclassredis.dao.ProductMapper; import net.xdclass.xdclassredis.model.ProductDO; import net.xdclass.xdclassredis.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Service;import java.util.HashMap; import java.util.Map;@Service public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductMapper productMapper;@Override@Caching(cacheable = {@Cacheable(value = {"product"},key = "#root.args[0]"),@Cacheable(value = {"product"},key = "'xdclass_'+#root.args[0]")},put = {@CachePut(value = {"product_test"},key="#id", cacheManager = "cacheManager1Minute")})public ProductDO findById(int id) {return productMapper.selectById(id);}}總結
以上是生活随笔為你收集整理的SpringCache与Redis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小白如何使用pe电脑如何pe启动
- 下一篇: 怎么打开电脑独立显卡设置如何打开电脑设置