您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Springboot2.X中怎么切换redis库,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
#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
<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>
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; } }
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); }
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; } }
/** * @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; } }
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()); } }
使用Redis自带方法同时使用16个数据库,继续使用上面的pom文件依赖
切记:接下来这个适用于Springboot2.1.X的版本,包括2.0.X,2.2.X的版本目前通过以下不能实现数据库的切换。
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); } }
@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); }
两种方式jedis和StringRedisTemplate切换数据库,我更喜欢用jedis,使用SringRedisTemplate我就没有过多的把所有redis方法复制出来。
下面的是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; }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。