通过JedisConnectionFactory切换数据源(redis中的db0,db1...)

该博客介绍了如何在Java应用中配置JedisConnectionFactory,以便根据需求动态选择连接不同的Redis数据库(如db0, db1等)。内容包括配置文件`redis.properties`和`applicationContext-redis.xml`的设置,以及在控制器中实现数据源切换的方法。" 106946793,8185307,本地开发环境:K3s、Traefik 2与Kubernetes集成实践,"['Kubernetes', 'K3s', 'Traefik', 'ingress控制器']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

redis.properties

redis.maxTotal=200
redis.maxWaitMillis=1000
redis.timeout=3000
redis.testOnBorrow=true
redis.node1.host=127.0.0.1
redis.node1.port=6379
redis.dbIndex=1

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	<!-- 配置数据源 redis -->
    <!-- 配置JedisPoolConfig实例 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
 
    <!-- 配置JedisConnectionFactory -->
    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.node1.host}" />
        <property name="port" value="${redis.node1.port}" />
        <property name="database" value="${redis.dbIndex}" />
        <property name="timeout" value="${redis.timeout}"></property>
        <property name="poolConfig" ref="poolConfig" />
    </bean>
    <!--redis操作模版,使用该对象可以操作redis  -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >    
        <property name="connectionFactory" ref="jedisConnectionFactory" />    
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->    
        <property name="keySerializer" >    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    
        </property>    
        <property name="valueSerializer" >    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    
        </property>    
        <property name="hashKeySerializer">    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>    
        </property>    
        <property name="hashValueSerializer">    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>    
        </property>    
        <!--开启事务报错 资源不够  -->  
        <property name="enableTransactionSupport" value="false"></property>  
    </bean >
</beans>

controller:

```
@Autowired
	private RedisTemplate RedisTemplate;
	
	@Autowired
	private JedisConnectionFactory jedisConnectionFactory;
	@RequestMapping(value = "RedisDb", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String RedisDb(){
		//获取redis默认db1中的数据
		Object object = RedisTemplate.opsForValue().get("KW");
		System.out.println(object);
		//将db1切换到db0
		jedisConnectionFactory.setDatabase(0);
		Object object2 = RedisTemplate.opsForValue().get("CountAll");
		System.out.println(object2);
		return null;
	}
server.port=8999 server.servlet.context-path=/competition spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_competitionapply?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.filters=stat,wall,log4j spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.useGlobalDataSourceStat=true spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 spring.servlet.multipart.max-request-size=20MB spring.servlet.multipart.max-file-size=10MB mybatis.mapper-locations=classpath:mapper/*.xml mybatis.config-location=classpath:mybatis-config.xml spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.jedis.pool.max-active=200 spring.redis.jedis.pool.max-wait=-1ms spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.min-idle=0 spring.redis.lettuce.shutdown-timeout=1000ms logging.level.root=WARN logging.level.org.springframework.web=DEBUG logging.file=c:\\springboot\\info.log logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n logging.pattern.file=%d{yyyy/MM/dd-HH:mm:ss}? [%thread] %-5level %logger- %msg%n 这个是我的java配置文件
最新发布
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

渡生远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值