java mybaits 读写分离_springboot mybatis读写分离的一个实现方案

首先考虑使用缓存来处理,如果缓存不够用,再使用读写分离来实现

application.yml配置两个数据源

#默认使用配置

spring:

profiles:

active: dev

---

#开发配置

spring:

profiles: dev

datasource:

master:

jdbc-url: jdbc:mysql://localhost:3812/test

username: user

password: pwd

driver-class-name: com.mysql.jdbc.Driver

type: com.alibaba.druid.pool.DruidDataSource

slave:

jdbc-url: jdbc:mysql://localhost:3812/test

username: user

password: pwd

driver-class-name: com.mysql.jdbc.Driver

type: com.alibaba.druid.pool.DruidDataSource

Application.java 注意Mapper上加@Mapper注解,然后可以被扫描到

@SpringBootApplication

@EnableAutoConfiguration

@MapperScan("com.xx.mobile.group.dao")

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

DataSourceConfig.java 注意有三个DataSource

@Configuration

public class DataSourceConfig {

@Bean

@ConfigurationProperties("spring.datasource.master")

public DataSource masterDataSource() {

return DataSourceBuilder.create().build();

}

@Bean

@ConfigurationProperties("spring.datasource.slave")

public DataSource slave1DataSource() {

return DataSourceBuilder.create().build();

}

@Bean

public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,

@Qualifier("slave1DataSource") DataSource slave1DataSource) {

Map targetDataSources = new HashMap<>();

targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);

targetDataSources.put(DBTypeEnum.SLAVE, slave1DataSource);

DataSourceRouting myRoutingDataSource = new DataSourceRouting();

myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);

myRoutingDataSource.setTargetDataSources(targetDataSources);

return myRoutingDataSource;

}

}

DBType

public enum DBTypeEnum {

MASTER, SLAVE;

}

MybatisConfig 注意注入的DataSource,注意事务注解的order

@EnableTransactionManagement(order = 2)

@Configuration

public class MyBatisConfig {

@Resource(name = "myRoutingDataSource")

private DataSource myRoutingDataSource;

@Bean

public SqlSessionFactory sqlSessionFactory() throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

sqlSessionFactoryBean.setDataSource(myRoutingDataSource);

sqlSessionFactoryBean.setMapperLocations(

new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

return sqlSessionFactoryBean.getObject();

}

@Bean

public PlatformTransactionManager platformTransactionManager() {

return new DataSourceTransactionManager(myRoutingDataSource);

}

}

DataSourceRouting

public class DataSourceRouting extends AbstractRoutingDataSource {

@Override

protected Object determineCurrentLookupKey() {

return DBContextHolder.get();

}

}

DBContextHolder

public class DBContextHolder {

private static final ThreadLocal contextHolder = new ThreadLocal<>();

private static final AtomicInteger counter = new AtomicInteger(-1);

public static void set(DBTypeEnum dbType) {

contextHolder.set(dbType);

}

public static DBTypeEnum get() {

return contextHolder.get();

}

public static void master() {

set(DBTypeEnum.MASTER);

System.out.println("切换到master");

}

public static void slave() {

set(DBTypeEnum.SLAVE);

System.out.println("切换到slave");

}

}

使用从库注解UseSlaveDatabase

public @interface UseSlaveDatabase {

}

DataSourceAop 注意此切面的Order

@Aspect

@Component

public class DataSourceAop implements Ordered{

@Override

public int getOrder() {

return 0;

}

@Before("readPointcut()")

public void read() {

DBContextHolder.slave();

}

@Pointcut("@annotation(com.xx.mobile.config.UseSlaveDatabase)")

public void readPointcut() {

}

}

测试类

@RunWith(SpringRunner.class)

@SpringBootTest(classes = Application.class)

public class TestTask {

@Autowired

private ITaskService taskService;

@Test

public void save() throws Exception {

}

@Test

public void query() throws Exception {

//query方法可以用上面的注解

}

}

相关的service dao mapper entity没有写 原理:多个数据源汇集到一个数据源上(myRoutingDataSource),然后定义切面,遇到有UseSlaveDatabase注解就设置数据源为从库,默认使用主库,因为myRoutingDataSource.setDefaultTargetDataSource(masterDataSource); 注意数据源选择要在是事务之前,所以切面的order要注意。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个快速开发框架,MyBatis是一款优秀的ORM框架,结合两者可以轻松实现分页查询。下面是一个简单的Java代码示例,用于实现分页查询: 1. 首先,在pom.xml文件中添加MyBatis和PageHelper的依赖: ```xml <!-- MyBatis依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!-- PageHelper依赖 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.13</version> </dependency> ``` 2. 在application.yml文件中配置MyBatis和PageHelper: ```yml mybatis: mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true pagehelper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql ``` 3. 在DAO层定义分页查询接口: ```java public interface UserDao { List<User> findUsersByPage(int pageNum, int pageSize); } ``` 4. 在Mapper XML文件中定义SQL语句: ```xml <select id="findUsersByPage" resultType="User"> select * from user </select> ``` 5. 在Service层实现分页查询方法: ```java @Service public class UserService { @Autowired private UserDao userDao; public PageInfo<User> findUsersByPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userDao.findUsersByPage(pageNum, pageSize); return new PageInfo<>(userList); } } ``` 6. 在Controller层调用Service方法: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public PageInfo<User> getUsers(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) { return userService.findUsersByPage(pageNum, pageSize); } } ``` 以上代码使用了PageHelper进行分页操作,最终将分页信息封装在了PageInfo对象中返回给调用者。你可以根据自己的实际情况进行修改和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值