iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring Boot集成redis,key自定义生成方式
  • 196
分享到

Spring Boot集成redis,key自定义生成方式

2024-04-02 19:04:59 196人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

一)自定义Redis key生成策略 @Configuration:表示当前类属于一个配置类,类似于一个spring.cfg.xml。 @EnableCaching:表示支持启用缓存

一)自定义Redis key生成策略

@Configuration:表示当前类属于一个配置类,类似于一个spring.cfg.xml。

@EnableCaching:表示支持启用缓存

自定义配置源码


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.cache.RedisCachePrefix;
import org.springframework.data.redis.core.RedisTemplate; 
import com.alibaba.fastJSON.jsON;
 

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
 
    
    @Bean
    public KeyGenerator cacheKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                // 由于参数可能不同, hashCode肯定不一样, 缓存的key也需要不一样
                sb.append(JSON.toJSONString(obj).hashCode());
            }
            return sb.toString();
        };
    }
 
    
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        redisCacheManager.setUsePrefix(true);
        // key缓存的前缀,以conf开头
        RedisCachePrefix cachePrefix = new RedisPrefix("conf");
        redisCacheManager.setCachePrefix(cachePrefix);
        // key缓存的过期时间, 600秒
        redisCacheManager.setDefaultExpiration(600L);
        return redisCacheManager;
    }
}

二)SpringBoot自带缓存方式

注解说明:

@Cacheable含义:当调用该注解声明的方法时,会先从缓存中查找,判断是否有key相同缓存的数据,如果有,就直接返回数据,如果没有,执行方法,然后把返回的数据以键值的方式存储到缓存中,方便下次同样参数请求时,直接从缓存中返回数据。

@Cacheable支持如下几个参数:

cacheNames:缓存位置的一段名称,不能为空,和value一个含义。

value:缓存位置的一段名称,不能为空,和cacheNames一个含义。

key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL。

keyGenerator:指定key的生成策略。

condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL。

@CacheEvict含义:当存在相同key的缓存时,把缓存清空,相当于删除。

@CacheEvict支持如下几个参数:

cacheNames:缓存位置的一段名称,不能为空,和value一个含义。

value:缓存位置的一段名称,不能为空,和cacheNames一个含义。

key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL。

condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL。

allEntries:true表示清除value中的全部缓存,默认为false。

测试代码:


package hk.com.cre.process.basic.service.impl; 
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable; 
public class RdisCacheTest {
 
    
    @Cacheable(cacheNames = "redis", keyGenerator = "cacheKeyGenerator")
    public String getRedisString(String param1, String param2) {
        return param1+":"+param2;
    }
	
    
    @CacheEvict(cacheNames = "redis", allEntries = true)
    public String cleanCache() {
        return "success";
    }
}

Spring Cache – KeyGenerator自定义rediskey

1. 概述

在此教程中,我们将演示如何使用 Spring Cache 创建自定义密钥生成器。

2. KeyGenerator

这负责为缓存中的每个数据项生成每个键,这些键将用于在检索时查找数据项。

此处的默认实现是SimpleKeyGenerator –它使用提供的方法参数来生成密钥。这意味着,如果我们有两个使用相同的缓存名称和参数类型集的方法,则很有可能会导致冲突。

它还意味着缓存数据可以由另一种方法覆盖。

3. 自定义密钥生成器

密钥生成器只需要实现一个方法:


Object generate(Object object, Method method, Object... params)

如果未正确实现或使用,则可能导致覆盖缓存数据。

让我们来看看实现:


public class CustomKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        return target.getClass().getSimpleName() + "_"
          + method.getName() + "_"
          + StringUtils.arrayToDelimitedString(params, "_");
    }
}

之后,我们有两种可能的方式使用它;第一种是在应用程序Config中声明一个豆。

请务必指出,类必须从缓存配置支持或实现缓存配置程序扩展:


@EnableCaching
@Configuration
public class ApplicationConfig extends CachingConfigurerSupport {
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        Cache booksCache = new ConcurrentMapCache("books");
        cacheManager.setCaches(Arrays.asList(booksCache));
        return cacheManager;
    }
    @Bean("customKeyGenerator")
    public KeyGenerator keyGenerator() {
        return new CustomKeyGenerator();
    }
}

第二种方法是将其用于特定方法:


@Component
public class BookService {
    @Cacheable(value = "books", keyGenerator = "customKeyGenerator")
    public List<Book> getBooks() {
        List<Book> books = new ArrayList<>();
        books.add(new Book("The Counterfeiters", "André Gide"));
        books.add(new Book("Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
        return books;
    }
}

4. 结论

在本文中,我们探讨了实现自定义春季缓存的密钥生成器的方法。

与往常一样,示例的完整源代码可在 GitHub 上找到。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Spring Boot集成redis,key自定义生成方式

本文链接: https://www.lsjlt.com/news/128806.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作