崛起于Springboot2.0.X之切换redis数据库(45)

    (本篇博客已于2019-08-28 优化更新)

    题记:找一个像太阳一样的人,为你晒掉所有悲伤!

    正题:两种方式:jedis切换数据源和redis自带切换数据源(redis数据库:0-15,默认是0库)

1、application.properties
#redis
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=10000ms

spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-idle=8
2、pom文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>com.google.collections</groupId>
    <artifactId>google-collections</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
3、配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author:MuJiuTian
 * @Description:redis的配置,这里默认设置使用redis:0 数据库
 * @Date: Created in 下午11:27 2019/7/4
 */
@Configuration
@EnableCaching
public class RedisCacheConfiguration extends CachingConfigurerSupport {

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

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

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

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

    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWaitMillis;

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

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWaitMillis.substring(0,maxWaitMillis.length()-2)));
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port,Integer.valueOf(timeout.substring(0,timeout.length()-2)));
        return jedisPool;
    }
}
4、redis工具类
import java.util.List;
import java.util.Map;

public interface RedisService {
    
    String setex(String key, int seconds,String value,int index);

    String set(String key, String value,int index);

    String get(String key,int index);
}
5、redis具体实现类
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class CacheSingleService implements RedisService{

    @Autowired
    private JedisPool jedisPool;

    public void returnResource(Jedis jedis) {
        jedis.close();
    }

    public Jedis getResource(int index) {
        Jedis jedis = jedisPool.getResource();
        jedis.select(index);
        return jedis;
    }

    public String setex(String key, int seconds, String value,int index) {
        Jedis jedis = null;
        try {
            jedis = getResource(index);
            return jedis.setex(key, seconds, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    public String set(String key, String value,int index){
        Jedis jedis = null;
        try {
            jedis = getResource(index);
            return jedis.set(key, value);
        } finally {
            returnResource(jedis);
        }
    }
    public String get(String key,int index) {
        String value = null;
        Jedis jedis = null;
        try {
            jedis = getResource(index);
            value = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return value;
    }
}
6、枚举类
/**
 * @Author:MuJiuTian
 * @Description:通过枚举类选择redis使用的数据库,一般公司的redis会分不同的数据到不同的库,比如用户信息到0库
 * 商品数据放在第二个库,运动数据放在第三库等等跟随项目分配而分配
 * @Date: Created in 下午10:13 2019/7/29
 */
public enum RedisPartition {
    //以下分别代表redis 0-15库
    INFO(0),
    One(1),
    Two(2),
    THREE(3),
    FOUR(4),
    FIVE(5),
    SIX(6),
    SEVEN(7),
    EIGHT(8),
    NINE(9),
    TEN(10),
    ELEVEN(11),
    TWELVE(12),
    THIRTEEN(13),
    FOURTEEN(14),
    FIFTEEN(15);

    private int ordinal;
    //构造方法
    RedisPartition(int ordinal) {
        this.ordinal = ordinal;
    }

    public void setOrdinal(int dbNum) {
        this.ordinal = dbNum;
    }

    public int getOrdinal() {
        return ordinal;
    }

    @Override
    public String toString() {
        return ""+ordinal;
    }
}
7、Controller层
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@Slf4j
public class TestController {
    @Autowired
    CacheSingleService singleService;

    @GetMapping("/test3")
    public String test3() {
        String key = "osc";
        String str = "i love osc";
        //存放在5数据库,默认是0
        singleService.set(key,"iloveyou",RedisPartition.SIX.getOrdinal());
        //存放在4数据库,默认是0
        singleService.set(str+"ii","iloveyou",RedisPartition.FIVE.getOrdinal());
        return "SUCCESS";
    }

    @GetMapping(value = "/test4")
    public String test4(){

        String key = "osc";
        String str = "i love osc";

        //查询5数据库内容
        String str1 = singleService.get(key,RedisPartition.SIX.getOrdinal());

        //查询4数据库内容
        String str2 = singleService.get(str,RedisPartition.FIVE.getOrdinal());

        return str1+str2;
    }

    public static void main(String[] args) {
        System.out.println(RedisPartition.FIFTEEN.getOrdinal());
    }
}
8、测试结果

31b0adac400e68eb4ad52905348ed5557e5.jpg

77b5d8c08240e5b07f55d8fd255f3bf28db.jpg

    使用Redis自带方法同时使用16个数据库,继续使用上面的pom文件依赖

9、Redis工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setDataBase(int num) {
        LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        if (connectionFactory != null && num != connectionFactory.getDatabase()) {
            connectionFactory.setDatabase(num);
            this.redisTemplate.setConnectionFactory(connectionFactory);
            connectionFactory.resetConnection();
        }
    }

    public StringRedisTemplate getRedisTemplate() {
        return this.redisTemplate;
    }

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    //获取指定key的值
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
10、Controller测试
@Autowired
RedisUtil redisUtil;

@GetMapping("/test")
public String test(String key) {
    for (int i = 1; i < 3; i++) {
        redisUtil.setDataBase(i);
        redisUtil.set(key, "" + i + key);
    }
    //开发环境用下面的代码,上面纯简单测试去不同的redis数据库而已
    //redisUtil.setDataBase(RedisPartition.EIGHT.getOrdinal());
    
    return redisUtil.get(key);
}

8c96bd2e0c4b83ab9451ac081fefffb1862.jpg

 

5a07e3774b190ab462f0be0ff2782306928.jpg

11、总结

      两种方式jedis和StringRedisTemplate切换数据库,我更喜欢用jedis,使用SringRedisTemplate我就没有过多的把所有redis方法复制出来。

12、附加

    下面的是ssm框架切换同时使用redis数据库的配置,至于redis.xml和redis.properties从网上copy一下吧

@Resource(name="stringRedisTemplate")
   private StringRedisTemplate stringRedisTemplate;

private StringRedisTemplate choseConnection(RedisConnectionEnum redisEnum){
   JedisConnectionFactory factory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
   factory.setDatabase(redisEnum.getDbNum());
   stringRedisTemplate.setConnectionFactory(factory);
   return stringRedisTemplate;
   }

    希望能够对各位有所帮助,如有bug,请评论或者私信,谢啦。

转载于:https://my.oschina.net/mdxlcj/blog/3081159

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值