SpringBoot+redis RedisTemplate/jedis 配置多个数据源 灵活切库 选择库

目录

1.这里也介绍两种方式  一种是redis的 RedisTemplate 另一种是jedis 大家需要哪一种 自己选择

2.这里先说redis 的 RedisTemplate

1.加入依赖并在在yml 文件里面加入配置

2.添加配置文件 

3.在jidis 里面配置多库 切换

1.加入依赖


1.这里也介绍两种方式  一种是redis的 RedisTemplate 另一种是jedis 大家需要哪一种 自己选择

2.这里先说redis 的 RedisTemplate

1.加入依赖并在在yml 文件里面加入配置
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
spring:
  redis:
    host: url
    port: 6379
    timeout: 3000
    pool:
      max-active: 100
      max-idle: 3
      min-idle: 0
      max-wait: -1
    password: 123456
    database:
      db10: 10
      db4: 4

我这里选择redis的 10号库和4号库,如果不同 请自行添加 db0:0 比如再添加一个0号库使用

2.添加配置文件 
package com.example.suntaesales.config;

/**
 * @author wangc
 * @date 2023/6/19 16:35
 */

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;


@Configuration
public class RedisConfig {

    @Value("${spring.redis.database.db10}")
    private int db10;

    @Value("${spring.redis.database.db4}")
    private int db4;


    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWait;

    @Bean
    public GenericObjectPoolConfig getPoolConfig(){
        // 配置redis连接池
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    private RedisConnectionFactory getFactory(int database) {
        // 构建工厂对象
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        config.setPassword(RedisPassword.of(password));
        LettucePoolingClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout))
                .poolConfig(getPoolConfig())
                .build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfig);
        // 设置使用的redis数据库
        factory.setDatabase(database);
        // 重新初始化工厂
        factory.afterPropertiesSet();
        return factory;
    }

    @NotNull
    private RedisTemplate<String, Object> getObjectRedisTemplate() {
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        RedisSerializer<Object> valueSerializer = new GenericFastJsonRedisSerializer();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }

    @Bean("redisTemplate")
    //加这个注解表示默认使用 也就是 主库的意思 我这里默认使用10号
    @Primary
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = getObjectRedisTemplate();
        redisTemplate.setConnectionFactory(this.getFactory(db10));
        return redisTemplate;
    }


    @Bean("stringRedisTemplate")
    @Primary  
    public StringRedisTemplate stringRedisTemplate() {
        RedisConnectionFactory factory = getFactory(db10);
        return new StringRedisTemplate(factory);
    }


    @Bean("stringRedisTemplate2")
    public StringRedisTemplate getRedisTemplate2(){
        RedisConnectionFactory factory = getFactory(db4);
        return new StringRedisTemplate(factory);
    }

    @Bean("redisTemplate2")
    public RedisTemplate<String, Object> redisTemplate2() {
        RedisTemplate<String, Object> redisTemplate = getObjectRedisTemplate();
        redisTemplate.setConnectionFactory(this.getFactory(db4));
        return redisTemplate;
    }



}

 3.在代码中引用  就可以正常使用redis了

  // 这里跟 name的值 跟在  RedisConfig的 @Bean("redisTemplate")
    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;
  // 这里跟 name的值 跟在  RedisConfig的 @Bean("redisTemplate2")
    @Resource(name = "redisTemplate2")
    private RedisTemplate redisTemplate2;
    

3.在jedis 里面配置多库 切换

1.加入依赖
        <!--    redis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
            <scope>compile</scope>
        </dependency>

package com.example.chassis.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.chassis.utils.Exception.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * @author wangc
 * redis 连接工具
 *  获取redis连接池
 * @date 2022/7/25 19:35
 */
public final class RedisUtils {
    private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
    //Redis服务器地址
    private static String redisHost = "url";
    //Redis服务端口
    private static Integer redisPort = 6379;
    //Redis密码
    private static String redisPassword = "密码";
    //Redis可连接实例最大数目
    private static Integer redisMaxTotal = 1000;
    //Redis最多有多少个状态为idle(空闲)的jedis实例,默认值是8
    //总是溢出
    private static Integer redisMaxIdle = 100;
    //Reids等待可用连接的最大时间,单位是毫秒,默认值为-1,表示永不超时。
    private static Integer redisMaxWaitNillis = 5000;
    //Redis设置超时时间
    private static Integer redisTimeOut = 3600;

    //在borrow(用)一个jedis实例时,是否提前进行validate(验证)操作;
    private static Boolean redisTestOnBorrow = true;
    private static JedisPool jedisPool = null;

    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(redisMaxTotal);
            config.setMaxIdle(redisMaxIdle);
            config.setMaxWaitMillis(redisMaxWaitNillis);
            config.setTestOnBorrow(redisTestOnBorrow);
            jedisPool = new JedisPool(config, redisHost, redisPort, redisTimeOut, redisPassword);
        } catch (Exception e) {
            log.warn("Redis初始化失败{}", e.getMessage());
        }
    }

    //获取连接池对象
    public synchronized static Jedis getJedisPool(int index) {
        try {
            if (jedisPool != null) {
                Jedis jedis = jedisPool.getResource();
                jedis.select(index);
                return jedis;
            } else {
                log.warn("获取Redis对象失败");
                return null;
            }
        } catch (Exception e) {
            log.warn("获取Redis对象失败{}", e.getMessage());
            return null;
        }
    }

    //关闭redis连接池
    public static void close() {
        if (jedisPool != null) {
            jedisPool.close();
        }
    }

    /**
     * JSON数据,转成Object对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return JSON.parseObject(json, clazz);
        } catch (Exception e) {
            log.warn("redis value fromJson error. msg: {}, value: {}, class: {}", e.getMessage(), json, clazz);
        }
        return null;
    }

    /**
     * Object转成JSON数据
     */
    public static String toJson(Object object) {
        try {
            if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                    object instanceof Double || object instanceof Boolean || object instanceof String) {
                return String.valueOf(object);
            }
            return JSON.toJSONString(object);
        } catch (Exception e) {
            log.warn("value toJson error. msg: {}, object: {}", e.getMessage(), object);
        }
        return null;
    }

    /**
     * redis get
     */
    public static <T> T get(Integer index, String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedisPool(index);
            String value = jedis.get(key);
            return value == null ? null : fromJson(value, clazz);
        } catch (Exception e) {
            log.warn(" redis get operation error. msg: {} index: {}, key: {}, class: {}", e.getMessage(), index, key, clazz);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * api 根据token获取登录信息
     *
     * @param token
     * @return
     */
    public static JSONObject get_login_user_info(String token) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(14);
            return JSONObject.parseObject(jedis.get("suntae:chassis:api:" + token));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * web 根据token获取登录信息
     *
     * @param token
     * @return
     */
    public static JSONObject get_login_user_info_web(String token) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(14);
            return JSONObject.parseObject(jedis.get("suntae:chassis:web:" + token));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * @param index
     * @param key
     * @param default_str
     * @return
     */
    public static String get_redis_value(int index, String key, String default_str) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            String value = jedis.get(key);
            if (value == null) {
                RedisConfig.redis_config();
                value = jedis.get(key);
                if (value == null) {
                    value = default_str;
                }
            }
            return value;
        } catch (Exception e) {// 抛错 说明JSON字符不是数组或根本就不是JSON
            System.out.println("get_redis_value : " + e.getMessage());
        } finally {
            if (jedis != null) {
                jedis.close();
            }

        }
        return default_str;
    }

    /**
     * 设置 key and value
     *
     * @param index
     * @param key
     * @param value
     * @return
     */
    public static boolean set_redis_K_V(int index, String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            jedis.set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 设置 key value time
     *
     * @param index
     * @param key
     * @param value
     * @param nx
     * @param ex
     * @param time
     * @return
     */
    public static boolean set_redis_K_V_json(int index, String key, String value, String nx, String ex, int time) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            jedis.set(key, value, nx, ex, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 删除键值
     *
     * @param index
     * @param key
     * @return
     */
    public static boolean del_redis_K(int index, String key) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            jedis.del(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 设置key过期时间
     *
     * @param index
     * @param key
     * @param ttl
     * @return
     */
    public static boolean set_redis_ttl(int index, String key, int ttl) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            jedis.expire(key, ttl);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;

    }

    /**
     * 获取key过期时间
     *
     * @param index
     * @param key
     * @return
     */
    public static Long get_redis_ttl(int index, String key) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            return jedis.ttl(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return 0L;
    }

    /**
     * 设置键值对不失效
     *
     * @param index
     * @param key
     * @return
     */
    public static Long redis_never_disappear(int index, String key) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            return jedis.persist(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return 0L;
    }

    /**
     * 左插入队列
     *
     * @param index
     * @param key
     * @param value
     * @return
     */
    public static boolean l_push(int index, String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            jedis.lpush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * <span style="background-color:red">右出队</span>
     *
     * @param index 选择库
     * @param key 键
     * @return string-结果集
     */
    public static String r_pop(int index, String key) {
        Jedis jedis = null;
        try {
            jedis = getJedisPool(index);
            return jedis.rpop(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return "";
    }

    public static JSONObject getRedisUserInfo(String account, int index, String token) {
        String str;
        try ( Jedis jedis = RedisUtils.getJedisPool(index)) {
            str = jedis.get("suntae:cloud_platform_control:chassis_center:" + account + ":" + token);
        }
        if (str == null) {
            throw new MyException(-9999,"token非法,请刷新验证码");
        }
        return ObjectMapperUtils.deserialize(str, JSONObject.class);
    }

}

package com.example.chassis.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.chassis.entity.Config;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author wangc
 * redis配置类
 * @date 2022/7/25 19:51
 */
public class RedisConfig {
    /**
     * 配置表中的数据拿到
     *
     * @return
     */
    public static List<Config> db_opp() {
        List<Config> list = new ArrayList<>();
        try {
            Connection connection = DBUtil.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from operating_config");
            if (resultSet != null) {
                while (resultSet.next()) {
                    Config config = new Config();
                    config.setKey(resultSet.getString("key"));
                    config.setGroup(resultSet.getString("group"));
                    config.setValue(resultSet.getString("value"));
                    config.setStatus(resultSet.getInt("status"));
                    list.add(config);
                   
                }
                return list;
            }
            //用完关闭流
            resultSet.close();
            statement.close();
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 数据放到redis的方法
     *
     * @return
     */
    public static Object redis_config() {
        List<Config> configs = db_opp();
        String key = "";
        for (int i = 0; i < configs.size(); i++) {
            if(configs.get(i).getStatus()==1){
                key = "config:" + configs.get(i).getGroup() + ":" + configs.get(i).getKey();
                RedisUtils.del_redis_K(6, key);
                RedisUtils.set_redis_K_V_json(6, key,configs.get(i).getValue() , "NX", "EX", 2000);
                RedisUtils.redis_never_disappear(6, key);
            }
        }
        return "success";
    }

    /**
     * json转换为Map<string,string>
     *
     * @param data
     * @return
     * @throws JSONException
     */
    public static Map<String, String> Json2UserDefine(String data) throws JSONException {
        Map<String, String> items = new HashMap<>();
        if (data.equals("")) return items;

        JSONArray array = JSONObject.parseArray(data);
        JSONObject object = null;
        for (int i = 0; i < array.size(); i++) {
            object = array.getJSONObject(i);
            String key = object.getString("title");
            String value = object.getString("url");
            items.put(key, value);
        }
        return items;
    }

    /**
     * JSON 转换为 map
     *
     * @param data
     * @return
     */
    public static Map<Double, Double> JsonToDouble(String data) {
        Map<Double, Double> items = new HashMap<>();
        if (data.equals("")) return items;
        JSONArray array = JSONObject.parseArray(data);
        JSONObject object = null;
        for (int i = 0; i < array.size(); i++) {
            object = array.getJSONObject(i);
            String key = object.getString("lat");//精度
            String value = object.getString("lon");//纬度
            items.put(Double.parseDouble(key), Double.parseDouble(value));
        }
        return items;
    }
}

 3.在代码中使用

        try (Jedis jedis = RedisUtils.getJedisPool(13)) {
//这里使用13号库 下面正常写自己的逻辑 try 会自动释放 关闭
            if (tboxConfigure.getStatus() == 1) {
// 使用jedis 操作redis  这里是删除
                jedis.del("suntae:online_status:" + tboxConfigureMapper.selectById(id).getOldVin() + ":tbox");
            }
        }

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值