springboot通过Druid实现redis+mysql的读写分离示例
时间: 2023-02-20 12:27:21 浏览: 122
Springboot可以通过Druid实现redis和mysql的读写分离,下面是一个示例:
1. 在pom.xml中添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2. 在application.yml中配置redis和mysql的读写分离:
spring:
datasource:
druid:
# Redis数据源
redis:
url: jdbc:redis://127.0.0.1:6379/0
driver-class-name: com.alibaba.druid.pool.DruidDataSource
username: root
password: root
# MySQL数据源
mysql:
url: jdbc:mysql://127.0.0.1:3306/test
driver-class-name: com.alibaba.druid.pool.DruidDataSource
username: root
password: root
3. 在Springboot启动类中添加@EnableDruid注解:
@SpringBootApplication
@EnableDruid
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4. 配置Druid数据源:
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.redis")
public DataSource redisDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.mysql")
public DataSource mysqlDataSource() {
return DruidDataSourceBuilder.create().build();
}
}
5. 在Service层中实现读写分离:
@Service
public class UserService {
@Autowired
private DataSource redisDataSource;
@Autowired
private DataSource mysqlDataSource;
public void saveUser() {
// 使用MySQL数据源写入数据
DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MYSQL);
// ...
// 使用Redis数据源读取数据
DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.REDIS);
// ...
}
}
阅读全文