当前位置: 代码网 > it编程>编程语言>Java > SpringBoot实现缓存组件配置动态切换的步骤详解

SpringBoot实现缓存组件配置动态切换的步骤详解

2024年07月26日 Java 我要评论
一、需求背景现在有多个springboot项目,但是不同的项目中使用的缓存组件是不一样的,有的项目使用redis,有的项目使用ctgcache,现在需要用同一套代码通过配置开关,在不同的项目中切换这两

一、需求背景

现在有多个springboot项目,但是不同的项目中使用的缓存组件是不一样的,有的项目使用redis,有的项目使用ctgcache,现在需要用同一套代码通过配置开关,在不同的项目中切换这两种缓存。

二、实现缓存组件的动态切换

1.第一步:配置文件新增切换开关

#缓存组件配置
#cache.type=ctgcache
cache.type=redis

2.第二步:创建ctgcache 缓存条件类

package com.gstanzer.supervise.cache;
 
import org.springframework.context.annotation.condition;
import org.springframework.context.annotation.conditioncontext;
import org.springframework.core.env.environment;
import org.springframework.core.type.annotatedtypemetadata;
 
/**
 * ctgcache 缓存条件类
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:31
 */
public class ctgcachecondition implements condition {
 
    @override
    public boolean matches(conditioncontext context, annotatedtypemetadata metadata) {
        // 从 environment 中获取属性
        environment env = context.getenvironment();
        string cachetype = env.getproperty("cache.type");
 
        // 检查 cache.type 是否与 metadata 中的某个值匹配(这里简单比较字符串)
        // 注意:实际应用中可能需要更复杂的逻辑来确定 metadata 中的值
        // 这里我们假设 metadata 中没有特定值,仅根据 cache.type 判断
        if ("ctgcache".equalsignorecase(cachetype)) {
            // 使用 ctgcache
            return true;
        }
 
        // 如果没有明确指定,或者指定了其他值,我们可以选择默认行为
        // 这里假设默认不使用这个 bean
        return false;
    }
 
}

3.第三步:创建redis 缓存条件类

package com.gstanzer.supervise.cache;
 
import org.springframework.context.annotation.condition;
import org.springframework.context.annotation.conditioncontext;
import org.springframework.core.env.environment;
import org.springframework.core.type.annotatedtypemetadata;
 
/**
 * redis 缓存条件类
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:31
 */
public class rediscondition implements condition {
 
    @override
    public boolean matches(conditioncontext context, annotatedtypemetadata metadata) {
        // 从 environment 中获取属性
        environment env = context.getenvironment();
        string cachetype = env.getproperty("cache.type");
 
        // 检查 cache.type 是否与 metadata 中的某个值匹配(这里简单比较字符串)
        // 注意:实际应用中可能需要更复杂的逻辑来确定 metadata 中的值
        // 这里我们假设 metadata 中没有特定值,仅根据 cache.type 判断
        if ("redis".equalsignorecase(cachetype)) {
            // 使用 redis
            return true;
        }
 
        // 如果没有明确指定,或者指定了其他值,我们可以选择默认行为
        // 这里假设默认不使用这个 bean
        return false;
    }
 
}

4.第四步:创建缓存切换配置类

package com.gstanzer.supervise.cache;
 
import com.ctg.itrdc.cache.pool.ctgjedispool;
import com.ctg.itrdc.cache.pool.ctgjedispoolconfig;
import com.ctg.itrdc.cache.vjedis.jedis.jedispoolconfig;
import com.fasterxml.jackson.annotation.jsonautodetect;
import com.fasterxml.jackson.annotation.propertyaccessor;
import com.fasterxml.jackson.databind.objectmapper;
import org.apache.commons.pool2.impl.genericobjectpoolconfig;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.conditional;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.listener.redismessagelistenercontainer;
import org.springframework.data.redis.serializer.jackson2jsonredisserializer;
import org.springframework.data.redis.serializer.redisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;
import redis.clients.jedis.hostandport;
 
import java.util.arraylist;
import java.util.list;
 
/**
 * 缓存配置类
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:28
 */
@configuration
public class cacheconfig {
 
    @value("${access.cq.redis.host1}")
    private string reidshost1;
 
    @value("${access.cq.redis.host2}")
    private string reidshost2;
 
    @value("${access.cq.redis.port}")
    private int port;
 
    @value("${access.cq.redis.password}")
    private string password;
 
    @value("${access.cq.redis.group}")
    private string group;
 
    @value("${access.cq.redis.max-total}")
    private int maxtotal;
 
    @value("${access.cq.redis.max-idle}")
    private int maxidle;
 
    @value("${access.cq.redis.min-idle}")
    private int minidle;
 
    @value("${access.cq.redis.max-wait}")
    private int maxwait;
 
    @value("${access.cq.redis.period}")
    private int period;
 
    @value("${access.cq.redis.monitor-timeout}")
    private int monitortimeout;
 
    @bean
    @conditional(rediscondition.class)
    public redistemplate<string, object> redistemplate(redisconnectionfactory factory) {
        // 创建并返回redistemplate
        redistemplate<string, object> redistemplate = new redistemplate<>();
        redistemplate.setconnectionfactory(factory);
 
 
        redisserializer<string> redisserializer = new stringredisserializer();
        redistemplate.setkeyserializer(redisserializer);
        redistemplate.sethashkeyserializer(redisserializer);
 
        // 设置value的序列化器
        //使用jackson 2,将对象序列化为json
        jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
        //json转对象类,不设置默认的会将json转成hashmap
        objectmapper om = new objectmapper();
        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
 
        // json中会显示类型
//        om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
        jackson2jsonredisserializer.setobjectmapper(om);
        redistemplate.setvalueserializer(jackson2jsonredisserializer);
        redistemplate.sethashvalueserializer(jackson2jsonredisserializer);
        redistemplate.afterpropertiesset();
        return redistemplate;
    }
 
    @bean
    @conditional(rediscondition.class)
    public redismessagelistenercontainer redismessagelistenercontainer(redisconnectionfactory connectionfactory) {
        // 创建并返回redismessagelistenercontainer
        redismessagelistenercontainer container = new redismessagelistenercontainer();
        // 监听所有库的key过期事件
        container.setconnectionfactory(connectionfactory);
        return container;
    }
 
    @bean
    @conditional(ctgcachecondition.class)
    public ctgjedispool ctgjedispool() {
        // 创建并返回ctgjedispool
        list<hostandport> hostandportlist = new arraylist();
        hostandport host1 = new hostandport(reidshost1, port);
        hostandport host2 = new hostandport(reidshost2, port);
        hostandportlist.add(host1);
        hostandportlist.add(host2);
 
        genericobjectpoolconfig poolconfig = new jedispoolconfig();
        poolconfig.setmaxtotal(maxtotal); // 最大连接数(空闲+使用中)
        poolconfig.setmaxidle(maxidle); //最大空闲连接数
        poolconfig.setminidle(minidle); //保持的最小空闲连接数
        poolconfig.setmaxwaitmillis(maxwait); //借出连接时最大的等待时间
 
        ctgjedispoolconfig config = new ctgjedispoolconfig(hostandportlist);
        config.setdatabase(group)
                .setpassword(password)
                .setpoolconfig(poolconfig)
                .setperiod(period)
                .setmonitortimeout(monitortimeout);
 
        ctgjedispool pool = new ctgjedispool(config);
        return pool;
    }
}

5.第五步:创建缓存服务接口

package com.gstanzer.supervise.cache;
 
/**
 * 缓存服务接口
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:46
 */
public interface cacheservice {
 
    /**
     * 检查缓存中是否存在某个key
     *
     * @param key
     * @return
     */
    public boolean exists(final string key);
 
    /**
     * 获取缓存中对应key的value值
     *
     * @param key
     * @return
     */
    public string get(final string key);
 
    /**
     * 存入值到缓存,并设置有效期
     *
     * @param key
     * @param value
     * @param expiretime 有效期,单位s
     * @return
     */
    public boolean set(final string key, string value, int expiretime);
 
    /**
     * 存入值到缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final string key, string value);
 
    /**
     * 删除缓存对应的key值
     *
     * @param key
     * @return
     */
    public boolean del(final string key);
 
}

6.第六步:创建ctgcache实现类实现缓存服务接口

package com.gstanzer.supervise.cache;
 
import com.ctg.itrdc.cache.pool.ctgjedispool;
import com.ctg.itrdc.cache.pool.proxyjedis;
import com.gstanzer.supervise.ctgcache.ctgredisutil;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.context.annotation.conditional;
import org.springframework.stereotype.service;
 
import javax.annotation.resource;
 
/**
 * ctgcache 缓存方法实现
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:48
 */
@service
@conditional(ctgcachecondition.class)
public class ctgcacheservice implements cacheservice {
 
    private static logger logger = loggerfactory.getlogger(ctgredisutil.class);
 
    @resource
    private ctgjedispool ctgjedispool;
 
    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final string key) {
        boolean exists = false;
        proxyjedis jedis = new proxyjedis();
        try {
            jedis = ctgjedispool.getresource();
            exists = jedis.exists(key);
            jedis.close();
        } catch (throwable e) {
            logger.error(e.getmessage());
            jedis.close();
        } finally {
            // finally内执行,确保连接归还
            try {
                jedis.close();
            } catch (throwable ignored) {
 
            }
        }
        return exists;
    }
 
    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public string get(final string key) {
        string value = null;
        proxyjedis jedis = new proxyjedis();
        try {
            jedis = ctgjedispool.getresource();
            value = jedis.get(key);
            jedis.close();
        } catch (throwable e) {
            logger.error(e.getmessage());
            jedis.close();
        } finally {
            // finally内执行,确保连接归还
            try {
                jedis.close();
            } catch (throwable ignored) {
 
            }
        }
        return value;
    }
 
    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final string key, string value, int expiretime) {
        boolean result = false;
        proxyjedis jedis = new proxyjedis();
        try {
            jedis = ctgjedispool.getresource();
            jedis.setex(key, expiretime, value);
            result = true;
            jedis.close();
        } catch (throwable e) {
            logger.error(e.getmessage());
            jedis.close();
        } finally {
            // finally内执行,确保连接归还
            try {
                jedis.close();
            } catch (throwable ignored) {
 
            }
        }
        return result;
    }
 
    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final string key, string value) {
        boolean result = false;
        proxyjedis jedis = new proxyjedis();
        try {
            jedis = ctgjedispool.getresource();
            jedis.set(key, value);
            result = true;
            jedis.close();
        } catch (throwable e) {
            logger.error(e.getmessage());
            jedis.close();
        } finally {
            // finally内执行,确保连接归还
            try {
                jedis.close();
            } catch (throwable ignored) {
 
            }
        }
        return result;
    }
 
    /**
     * 删除缓存
     *
     * @param key
     * @return
     */
    public boolean del(final string key) {
        boolean result = false;
        proxyjedis jedis = new proxyjedis();
        try {
            jedis = ctgjedispool.getresource();
            jedis.del(key);
            result = true;
            jedis.close();
        } catch (throwable e) {
            logger.error(e.getmessage());
            jedis.close();
        } finally {
            // finally内执行,确保连接归还
            try {
                jedis.close();
            } catch (throwable ignored) {
 
            }
        }
        return result;
    }
 
}

7.第七步:创建redis实现类实现缓存服务接口

package com.gstanzer.supervise.cache;
 
import com.gstanzer.supervise.redis.redisutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.conditional;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.core.valueoperations;
import org.springframework.stereotype.service;
 
import java.io.serializable;
import java.util.concurrent.timeunit;
 
/**
 * reids 缓存方法实现
 *
 * @author: tangbingbing
 * @date: 2024/7/22 14:48
 */
@service
@conditional(rediscondition.class)
public class rediscacheservice implements cacheservice {
 
    @autowired
    private redistemplate redistemplate;
 
    @autowired
    private stringredistemplate stringredistemplate;
 
    private static logger logger = loggerfactory.getlogger(redisutils.class);
 
    /**
     * 检查缓存中是否存在某个key
     *
     * @param key
     * @return
     */
    @override
    public boolean exists(string key) {
        return redistemplate.haskey(key);
    }
 
    /**
     * 获取缓存中对应key的value值
     *
     * @param key
     * @return
     */
    @override
    public string get(string key) {
        string result = null;
        valueoperations<serializable, object> operations = redistemplate.opsforvalue();
        result = operations.get(key).tostring();
        return result;
    }
 
    /**
     * 存入值到缓存,并设置有效期
     *
     * @param key
     * @param value
     * @param expiretime 有效期,单位s
     * @return
     */
    @override
    public boolean set(string key, string value, int expiretime) {
        boolean result = false;
        try {
            valueoperations<serializable, object> operations = redistemplate.opsforvalue();
            operations.set(key, value);
            redistemplate.expire(key, expiretime, timeunit.seconds);
            result = true;
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }
 
    /**
     * 存入值到缓存
     *
     * @param key
     * @param value
     * @return
     */
    @override
    public boolean set(string key, string value) {
        boolean result = false;
        try {
            valueoperations<serializable, object> operations = redistemplate.opsforvalue();
            operations.set(key, value);
            result = true;
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }
 
    /**
     * 删除缓存对应的key值
     *
     * @param key
     * @return
     */
    @override
    public boolean del(string key) {
        boolean result = false;
        try {
            if (exists(key)) {
                redistemplate.delete(key);
            }
            result = true;
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }
}

8.第八步:在程序中注入缓存服务接口使用

package com.gstanzer.supervise.controller;
 
import com.gstanzer.supervise.cache.cacheservice;
import com.gstanzer.supervise.jwt.passtoken;
import com.gstanzer.supervise.swagger.apiforbackendiniam;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import io.swagger.annotations.apiparam;
import lombok.extern.slf4j.slf4j;
import org.springframework.validation.annotation.validated;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
 
import javax.annotation.resource;
import javax.validation.constraints.notempty;
 
 
/**
 * 缓存测试 controller
 *
 * @author: tangbingbing
 * @date: 2023/10/23 16:25
 */
@api(tags = "缓存测试")
@slf4j
@validated
@restcontroller
@requestmapping(value = "/redis")
public class rediscontroller {
 
 
    @resource
    private cacheservice cacheservice;
 
    @passtoken
    @apiforbackendiniam
    @apioperation(value = "redis测试")
    @postmapping("/test")
    public string test(
            @requestparam() @apiparam(value = "redis键") @notempty(message = "{validator.rediscontroller.test.key.notempty}") string key
    ) {
        string res = "获取到redis-value为:空";
        if (cacheservice.exists(key)){
            string value = cacheservice.get(key);
            res = "获取到redis-value为:" + value;
        } else {
            cacheservice.set(key,"test",60);
            res = "未获取到value,重新设置值有效期为60s";
        }
        return res;
    }
}

三、总结

其实整体实现是一个比较简单的过程,核心是需要了解springboot中@conditional注解的应用,希望对大家有所帮助。

到此这篇关于springboot实现缓存组件配置动态切换的步骤详解的文章就介绍到这了,更多相关springboot缓存组件动态切换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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