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

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

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
<think>好的,用户需要的是一个Spring Boot项目的完整配置示例,包含Druid数据源、MyBatis映射、Redis连接池和日志设置。首先,我得回忆一下各个组件的配置方式,尤其是结合用户提供的引用内容。 用户提到的引用[1]和[3]中提到了Druid的多数据源配置,使用DruidXADataSource,并且提到了在application.yml中配置两个数据源。而引用[2]推荐了dynamic-datasource-spring-boot-starter,但用户这里可能需要基础的配置,而不是多数据源的快速集成。所以可能需要展示基本的多数据源配置,或者根据用户的问题选择更通用的方式。 另外,用户还提到了MyBatis映射,所以需要配置mapper locations和typeAliases。Redis连接池的话,通常使用Lettuce或者Jedis,这里可能需要配置host、port、连接池参数。日志设置方面,通常用logback-spring.xml,配置控制台和文件输出。 需要注意引用中的配置示例,比如引用[1]中的配置结构,可能需要按照那个格式来展示。同时,引用[3]提到了@ConfigurationProperties注解,但用户现在需要的是配置文件的内容,所以应该集中在application.yml里。 可能需要分部分展示配置,每个部分对应不同的组件:数据源(Druid)、MyBatis、Redis、日志。每个部分的配置参数需要正确,比如Druid的连接池参数、监控页面的配置,MyBatis的mapper位置,Redis的连接池参数,以及日志的级别和输出方式。 另外,用户提到“完整配置示例”,所以可能需要给出一个综合的application.yml文件,包含所有相关配置,以及可能的其他配置文件如logback-spring.xml。同时,代码块需要正确的高亮和格式,比如yaml和xml的区分。 还需要检查是否有遗漏的配置项,比如Druid的过滤器配置,MyBatis的配置是否启用驼峰命名,Redis的超时设置,日志的滚动策略等。此外,是否需要事务管理相关的配置?比如引用[1]中提到了分布式事务,但用户的问题可能不需要,所以可能不需要包含Atomikos的部分。 最后,确保配置示例中的占位符(如数据库URL、用户名、密码)用示例值,并且注释说明各个部分的作用,方便用户理解。同时,根据引用内容,可能需要添加相关的依赖提示,比如Druid、MyBatis、Redis的starter依赖。</think>以下是一个包含Druid数据源、MyBatis映射、Redis连接池和日志配置的Spring Boot完整示例(application.yml): ```yaml # 公共配置 spring: profiles: active: dev # 数据源配置(多数据源示例) datasource: type: com.alibaba.druid.pool.DruidDataSource druid: one: url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver initial-size: 5 min-idle: 5 max-active: 20 filters: stat,wall web-stat-filter: enabled: true stat-view-servlet: enabled: true url-pattern: /druid/* two: # 第二个数据源配置[^3] url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8 username: root password: 123456 # ...其他参数同上 # Redis配置 redis: host: 127.0.0.1 port: 6379 password: database: 0 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1ms # MyBatis配置 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.domain configuration: map-underscore-to-camel-case: true cache-enabled: true # 日志配置 logging: level: root: INFO com.example: DEBUG file: name: logs/app.log pattern: console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" ``` 配套的logback-spring.xml示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/defaults.xml"/> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_FILE}</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <fileNamePattern>logs/app-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <maxFileSize>50MB</maxFileSize> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> </appender> <root level="${LOG_LEVEL:-INFO}"> <appender-ref ref="FILE"/> <appender-ref ref="CONSOLE"/> </root> </configuration> ``` 关键配置说明: 1. Druid数据源配置包含连接池参数和监控页配置[^1] 2. MyBatis配置了XML映射文件位置和驼峰转换规则[^4] 3. Redis连接池使用Lettuce实现,配置了连接池参数 4. 日志系统配置了文件输出和滚动策略 依赖建议(pom.xml): ```xml <dependencies> <!-- Druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.16</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

渡生远方

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

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

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

打赏作者

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

抵扣说明:

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

余额充值