当前位置: 代码网 > it编程>编程语言>Java > SpringData实现自定义Redis缓存的序列化机制和过期策略

SpringData实现自定义Redis缓存的序列化机制和过期策略

2025年04月14日 Java 我要评论
引言在现代高并发分布式系统中,缓存扮演着至关重要的角色。spring data redis提供了强大的缓存抽象层,使开发者能够轻松地在应用中集成redis缓存。本文将深入探讨如何自定义redis缓存的

引言

在现代高并发分布式系统中,缓存扮演着至关重要的角色。spring data redis提供了强大的缓存抽象层,使开发者能够轻松地在应用中集成redis缓存。本文将深入探讨如何自定义redis缓存的序列化机制和过期策略,帮助开发者解决缓存数据一致性、内存占用和访问效率等关键问题。通过合理配置spring cache注解和rediscache实现,可显著提升应用性能,减轻数据库压力。

一、spring cache与redis集成基础

spring cache是spring框架提供的缓存抽象,它允许开发者以声明式方式定义缓存行为,而无需编写底层缓存逻辑。结合redis作为缓存提供者,可以构建高性能的分布式缓存系统。spring cache支持多种注解,如@cacheable、@cacheput、@cacheevict等,分别用于缓存查询结果、更新缓存和删除缓存。redis的高性能和丰富的数据结构使其成为理想的缓存存储选择。

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cache.annotation.enablecaching;

@springbootapplication
@enablecaching  // 启用spring缓存支持
public class rediscacheapplication {
    public static void main(string[] args) {
        springapplication.run(rediscacheapplication.class, args);
    }
}

二、redis缓存配置基础

配置redis缓存需要创建rediscachemanager和定义基本的缓存属性。rediscachemanager负责创建和管理rediscache实例,而rediscache则实现了spring的cache接口。基本配置包括设置redis连接工厂、默认过期时间和缓存名称前缀等。通过rediscacheconfiguration可以自定义序列化方式、过期策略和键前缀等。这些配置对缓存的性能和可用性有直接影响。

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.connection.redisconnectionfactory;

import java.time.duration;

@configuration
public class rediscacheconfig {

    @bean
    public rediscachemanager cachemanager(redisconnectionfactory connectionfactory) {
        // 创建默认的redis缓存配置
        rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig()
                // 设置缓存有效期为1小时
                .entryttl(duration.ofhours(1))
                // 设置键前缀
                .prefixcachenamewith("app:cache:");
        
        return rediscachemanager.builder(connectionfactory)
                .cachedefaults(config)
                .build();
    }
}

三、自定义序列化策略

默认情况下,spring data redis使用jdk序列化,这种方式存在效率低、占用空间大、可读性差等问题。自定义序列化策略可以显著改善这些问题。常用的序列化方式包括json、protobuf和kryo等。其中json序列化便于调试但性能一般,protobuf和kryo则提供更高的性能和更小的存储空间。选择合适的序列化方式需要在性能、空间效率和可读性之间做权衡。

import com.fasterxml.jackson.annotation.jsontypeinfo;
import com.fasterxml.jackson.databind.objectmapper;
import com.fasterxml.jackson.databind.jsontype.impl.laissezfairesubtypevalidator;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.cache.rediscacheconfiguration;
import org.springframework.data.redis.serializer.genericjackson2jsonredisserializer;
import org.springframework.data.redis.serializer.redisserializationcontext;
import org.springframework.data.redis.serializer.stringredisserializer;

@configuration
public class redisserializerconfig {

    @bean
    public rediscacheconfiguration cacheconfiguration() {
        // 创建自定义的objectmapper,用于json序列化
        objectmapper mapper = new objectmapper();
        // 启用类型信息,确保反序列化时能够正确恢复对象类型
        mapper.activatedefaulttyping(
                laissezfairesubtypevalidator.instance,
                objectmapper.defaulttyping.non_final,
                jsontypeinfo.as.property
        );
        
        // 创建基于jackson的redis序列化器
        genericjackson2jsonredisserializer jsonserializer = 
                new genericjackson2jsonredisserializer(mapper);
        
        // 配置redis缓存使用string序列化器处理键,json序列化器处理值
        return rediscacheconfiguration.defaultcacheconfig()
                .serializekeyswith(
                        redisserializationcontext.serializationpair.fromserializer(
                                new stringredisserializer()))
                .serializevalueswith(
                        redisserializationcontext.serializationpair.fromserializer(
                                jsonserializer));
    }
}

四、实现自定义序列化器

在某些场景下,spring提供的序列化器可能无法满足特定需求,此时需要实现自定义序列化器。自定义序列化器需要实现redisserializer接口,覆盖serialize和deserialize方法。通过自定义序列化器,可以实现特定对象的高效序列化,或者为序列化添加额外的安全措施,如加密解密等。实现时需注意处理序列化异常和空值情况。

import org.springframework.data.redis.serializer.redisserializer;
import org.springframework.data.redis.serializer.serializationexception;
import com.esotericsoftware.kryo.kryo;
import com.esotericsoftware.kryo.io.input;
import com.esotericsoftware.kryo.io.output;

import java.io.bytearrayoutputstream;

public class kryoredisserializer<t> implements redisserializer<t> {
    
    private final class<t> clazz;
    private static final threadlocal<kryo> kryothreadlocal = threadlocal.withinitial(() -> {
        kryo kryo = new kryo();
        // 配置kryo实例
        kryo.setregistrationrequired(false); // 不要求注册类
        return kryo;
    });
    
    public kryoredisserializer(class<t> clazz) {
        this.clazz = clazz;
    }
    
    @override
    public byte[] serialize(t t) throws serializationexception {
        if (t == null) {
            return new byte[0];
        }
        
        kryo kryo = kryothreadlocal.get();
        try (bytearrayoutputstream baos = new bytearrayoutputstream();
             output output = new output(baos)) {
            kryo.writeobject(output, t);
            output.flush();
            return baos.tobytearray();
        } catch (exception e) {
            throw new serializationexception("error serializing object using kryo", e);
        }
    }
    
    @override
    public t deserialize(byte[] bytes) throws serializationexception {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        
        kryo kryo = kryothreadlocal.get();
        try (input input = new input(bytes)) {
            return kryo.readobject(input, clazz);
        } catch (exception e) {
            throw new serializationexception("error deserializing object using kryo", e);
        }
    }
}

五、多级缓存配置

在实际应用中,往往需要为不同类型的数据配置不同的缓存策略。spring cache支持定义多个缓存,每个缓存可以有独立的配置。通过rediscachemanagerbuildercustomizer可以为不同的缓存名称定制配置,如设置不同的过期时间、序列化方式和前缀策略等。多级缓存配置能够针对业务特点优化缓存性能。

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.rediscachemanager.rediscachemanagerbuilder;
import org.springframework.data.redis.connection.redisconnectionfactory;

import java.time.duration;
import java.util.hashmap;
import java.util.map;

@configuration
public class multilevelcacheconfig {

    @bean
    public rediscachemanager cachemanager(redisconnectionfactory connectionfactory,
                                          rediscacheconfiguration defaultconfig) {
        // 创建不同缓存空间的配置映射
        map<string, rediscacheconfiguration> configmap = new hashmap<>();
        
        // 用户缓存:过期时间30分钟
        configmap.put("usercache", defaultconfig.entryttl(duration.ofminutes(30)));
        
        // 产品缓存:过期时间2小时
        configmap.put("productcache", defaultconfig.entryttl(duration.ofhours(2)));
        
        // 热点数据缓存:过期时间5分钟
        configmap.put("hotdatacache", defaultconfig.entryttl(duration.ofminutes(5)));
        
        // 创建并配置rediscachemanager
        return rediscachemanager.builder(connectionfactory)
                .cachedefaults(defaultconfig)
                .withinitialcacheconfigurations(configmap)
                .build();
    }
}

六、自定义过期策略

缓存过期策略直接影响缓存的有效性和资源消耗。spring data redis支持多种过期设置方式,包括全局统一过期时间、按缓存名称设置过期时间,以及根据缓存内容动态设置过期时间。合理的过期策略有助于平衡缓存命中率和数据新鲜度。对于不同更新频率的数据,应设置不同的过期时间以获得最佳效果。

import org.springframework.cache.interceptor.keygenerator;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.cache.cachekeyprefix;
import org.springframework.data.redis.cache.rediscache;
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 java.lang.reflect.method;
import java.time.duration;
import java.util.objects;

@configuration
public class customexpirationconfig {

    @bean
    public rediscachemanager cachemanager(redisconnectionfactory connectionfactory) {
        // 创建自定义的rediscachewriter
        rediscachewriter cachewriter = rediscachewriter.nonlockingrediscachewriter(connectionfactory);
        
        // 默认缓存配置
        rediscacheconfiguration defaultconfig = rediscacheconfiguration.defaultcacheconfig()
                .entryttl(duration.ofhours(1)); // 默认过期时间1小时
        
        // 创建支持动态ttl的rediscachemanager
        return new dynamicttlrediscachemanager(cachewriter, defaultconfig);
    }
    
    // 自定义缓存键生成器,考虑方法名和参数
    @bean
    public keygenerator customkeygenerator() {
        return new keygenerator() {
            @override
            public object generate(object target, method method, object... params) {
                stringbuilder sb = new stringbuilder();
                sb.append(target.getclass().getsimplename())
                  .append(":")
                  .append(method.getname());
                
                for (object param : params) {
                    if (param != null) {
                        sb.append(":").append(param.tostring());
                    }
                }
                
                return sb.tostring();
            }
        };
    }
    
    // 自定义rediscachemanager,支持动态ttl
    static class dynamicttlrediscachemanager extends rediscachemanager {
        
        public dynamicttlrediscachemanager(rediscachewriter cachewriter,
                                          rediscacheconfiguration defaultconfig) {
            super(cachewriter, defaultconfig);
        }
        
        @override
        protected rediscache createrediscache(string name, rediscacheconfiguration config) {
            // 根据缓存名称动态设置ttl
            if (name.startswith("useractivity")) {
                config = config.entryttl(duration.ofminutes(15));
            } else if (name.startswith("product")) {
                config = config.entryttl(duration.ofhours(4));
            } else if (name.startswith("config")) {
                config = config.entryttl(duration.ofdays(1));
            }
            
            return super.createrediscache(name, config);
        }
    }
}

七、缓存注解的高级应用

spring cache提供了丰富的注解用于管理缓存,包括@cacheable、@cacheput、@cacheevict和@caching等。这些注解能够精细控制缓存行为,如何何时缓存结果、更新缓存和清除缓存。通过condition和unless属性,可以实现条件缓存,只有满足特定条件的结果才会被缓存。合理使用这些注解可以提高缓存的命中率和有效性。

import org.springframework.cache.annotation.cacheable;
import org.springframework.cache.annotation.cacheput;
import org.springframework.cache.annotation.cacheevict;
import org.springframework.cache.annotation.caching;
import org.springframework.stereotype.service;

@service
public class productservice {

    private final productrepository repository;
    
    public productservice(productrepository repository) {
        this.repository = repository;
    }
    
    /**
     * 根据id查询产品,结果会被缓存
     * 条件:产品价格大于100才缓存
     */
    @cacheable(
        value = "productcache",
        key = "#id",
        condition = "#id > 0",
        unless = "#result != null && #result.price <= 100"
    )
    public product findbyid(long id) {
        // 模拟从数据库查询
        return repository.findbyid(id).orelse(null);
    }
    
    /**
     * 更新产品信息并更新缓存
     */
    @cacheput(value = "productcache", key = "#product.id")
    public product updateproduct(product product) {
        return repository.save(product);
    }
    
    /**
     * 删除产品并清除相关缓存
     * allentries=true表示清除所有productcache的缓存项
     */
    @cacheevict(value = "productcache", key = "#id", allentries = false)
    public void deleteproduct(long id) {
        repository.deletebyid(id);
    }
    
    /**
     * 复合缓存操作:同时清除多个缓存
     */
    @caching(
        evict = {
            @cacheevict(value = "productcache", key = "#id"),
            @cacheevict(value = "categoryproductscache", key = "#product.categoryid")
        }
    )
    public void deleteproductwithrelations(long id, product product) {
        repository.deletebyid(id);
    }
}

八、实现缓存预热与更新策略

缓存预热是指在系统启动时提前加载热点数据到缓存中,以避免系统启动初期大量缓存未命中导致的性能问题。缓存更新策略则关注如何保持缓存数据与数据库数据的一致性。常见的更新策略包括失效更新、定时更新和异步更新等。合理的缓存预热与更新策略能够提高系统的响应速度和稳定性。

import org.springframework.boot.commandlinerunner;
import org.springframework.cache.cachemanager;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;

import java.util.list;
import java.util.concurrent.timeunit;

@component
public class cachewarmer implements commandlinerunner {

    private final productrepository productrepository;
    private final cachemanager cachemanager;
    private final redistemplate<string, object> redistemplate;
    
    public cachewarmer(productrepository productrepository,
                       cachemanager cachemanager,
                       redistemplate<string, object> redistemplate) {
        this.productrepository = productrepository;
        this.cachemanager = cachemanager;
        this.redistemplate = redistemplate;
    }
    
    /**
     * 系统启动时执行缓存预热
     */
    @override
    public void run(string... args) {
        system.out.println("performing cache warming...");
        
        // 加载热门产品到缓存
        list<product> hotproducts = productrepository.findtop100byorderbyviewsdesc();
        for (product product : hotproducts) {
            string cachekey = "productcache::" + product.getid();
            redistemplate.opsforvalue().set(cachekey, product);
            
            // 设置差异化过期时间,避免同时过期
            long randomttl = 3600 + (long)(math.random() * 1800); // 1小时到1.5小时之间的随机值
            redistemplate.expire(cachekey, randomttl, timeunit.seconds);
        }
        
        system.out.println("cache warming completed, loaded " + hotproducts.size() + " products");
    }
    
    /**
     * 定时更新热点数据缓存,每小时执行一次
     */
    @scheduled(fixedrate = 3600000)
    public void refreshhotdatacache() {
        system.out.println("refreshing hot data cache...");
        
        // 获取最新的热点数据
        list<product> latesthotproducts = productrepository.findtop100byorderbyviewsdesc();
        
        // 更新缓存
        for (product product : latesthotproducts) {
            redistemplate.opsforvalue().set("productcache::" + product.getid(), product);
        }
    }
}

九、缓存监控与统计

缓存监控是缓存管理的重要组成部分,通过监控可以了解缓存的使用情况、命中率、内存占用等关键指标。spring boot actuator结合micrometer可以收集缓存统计数据并通过prometheus等监控系统进行可视化展示。通过监控数据可以及时发现缓存问题并进行优化,如调整缓存大小、过期时间和更新策略等。

import io.micrometer.core.instrument.meterregistry;
import io.micrometer.core.instrument.timer;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.around;
import org.aspectj.lang.annotation.aspect;
import org.springframework.stereotype.component;

import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.atomic.atomiclong;

@aspect
@component
public class cachemonitoraspect {

    private final meterregistry meterregistry;
    private final concurrenthashmap<string, atomiclong> cachehits = new concurrenthashmap<>();
    private final concurrenthashmap<string, atomiclong> cachemisses = new concurrenthashmap<>();
    
    public cachemonitoraspect(meterregistry meterregistry) {
        this.meterregistry = meterregistry;
    }
    
    /**
     * 监控缓存方法的执行情况
     */
    @around("@annotation(org.springframework.cache.annotation.cacheable)")
    public object monitorcacheable(proceedingjoinpoint joinpoint) throws throwable {
        string methodname = joinpoint.getsignature().toshortstring();
        timer.sample sample = timer.start(meterregistry);
        
        // 方法执行前标记,用于判断是否走了缓存
        boolean methodexecuted = false;
        
        try {
            object result = joinpoint.proceed();
            methodexecuted = true;
            return result;
        } finally {
            // 记录方法执行时间
            sample.stop(meterregistry.timer("cache.access.time", "method", methodname));
            
            // 更新缓存命中/未命中计数
            if (methodexecuted) {
                // 方法被执行,说明缓存未命中
                cachemisses.computeifabsent(methodname, k -> {
                    atomiclong counter = new atomiclong(0);
                    meterregistry.gauge("cache.miss.count", counter);
                    return counter;
                }).incrementandget();
            } else {
                // 方法未执行,说明命中缓存
                cachehits.computeifabsent(methodname, k -> {
                    atomiclong counter = new atomiclong(0);
                    meterregistry.gauge("cache.hit.count", counter);
                    return counter;
                }).incrementandget();
            }
        }
    }
}

总结

spring data redis缓存通过提供灵活的配置选项,使开发者能够根据业务需求自定义序列化方式和过期策略。合理的序列化机制可显著提升缓存效率,减少网络传输和存储空间消耗。而科学的过期策略则能平衡数据一致性和缓存命中率,避免缓存穿透和雪崩等问题。在实际应用中,缓存策略应结合业务特点进行差异化配置,如对热点数据设置较短过期时间以保证数据新鲜度,对变更不频繁的配置数据设置较长过期时间以减少数据库查询。通过缓存预热、更新策略和监控体系的建立,可以构建高性能、高可靠的分布式缓存系统,有效支撑大规模并发访问的业务需求。

到此这篇关于springdata实现自定义redis缓存的序列化机制和过期策略的文章就介绍到这了,更多相关springdata实现序列化机制和过期策略内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com