1. 项目结构
db 结构.png
package com.wudl.db.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName : DataSourceConfig
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:01
*/
@Configuration
@MapperScan(basePackages = {"com.wudl.db.mapper"},sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class DataSourceConfig {
@Value("${master.datasource.driver-class-name}")
private String masterDriverClassName;
@Value("${master.datasource.url}")
private String masterUrl;
@Value("${master.datasource.username}")
private String masterUsername;
@Value("${master.datasource.password}")
private String masterPassword;
@Value("${slave.datasource.driver-class-name}")
private String slaveDriverClassName;
@Value("${slave.datasource.url}")
private String slaveUrl;
@Value("${slave.datasource.username}")
private String slaveUsername;
@Value("${slave.datasource.password}")
private String slavePassword;
@Bean
public DruidDataSource masterDruidDataSource(){
DruidDataSource druidDataSource=new DruidDataSource();
druidDataSource.setDriverClassName(masterDriverClassName);
druidDataSource.setUrl(masterUrl);
druidDataSource.setUsername(masterUsername);
druidDataSource.setPassword(masterPassword);
return druidDataSource;
}
@Bean
public DruidDataSource salveDruidDataSource(){
DruidDataSource druidDataSource=new DruidDataSource();
druidDataSource.setDriverClassName(slaveDriverClassName);
druidDataSource.setUrl(slaveUrl);
druidDataSource.setUsername(slaveUsername);
druidDataSource.setPassword(slavePassword);
return druidDataSource;
}
@Bean
public MyDataSource myDataSource(DruidDataSource masterDruidDataSource,DruidDataSource salveDruidDataSource){
MyDataSource myDataSource=new MyDataSource();
myDataSource.setDefaultTargetDataSource(masterDruidDataSource);
Map dataSourceMap=new HashMap();
dataSourceMap.put("master",masterDruidDataSource);
dataSourceMap.put("slave",salveDruidDataSource);
myDataSource.setTargetDataSources(dataSourceMap);
return myDataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(MyDataSource myDataSource){
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(myDataSource);
return sqlSessionFactoryBean;
}
}
package com.wudl.db.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @ClassName : MyDataSource
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:02
*/
public class MyDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return MyThreadLocal.getDataSource();
}
}
package com.wudl.db.config;
/**
* @ClassName : MyThreadLocal
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:02
*/
public class MyThreadLocal {
public static final ThreadLocal<String> local=new ThreadLocal<String>();
public static String getDataSource(){
return local.get();
}
public static void setDataSource(String dataSource){
local.set(dataSource);
}
}
package com.wudl.db.model;
/**
* @ClassName : User
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:04
*/
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.wudl.db.service;
import com.wudl.db.config.MyThreadLocal;
import com.wudl.db.model.User;
import com.wudl.db.mapper.UserMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @ClassName : UserService
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:05
*/
@Service("userService")
public class UserService {
@Resource
private UserMapper userMapper;
public void add(User user){
//切换数据源为主库
MyThreadLocal.setDataSource("master");
userMapper.insert(user);
}
public List<User> selectAllMaster(){
//切换数据源为从库
MyThreadLocal.setDataSource("slave");
return userMapper.selectAll();
}
public List<User> selectAllSlave(){
//切换数据源为从库
MyThreadLocal.setDataSource("master");
return userMapper.selectAll();
}
}
package com.wudl.db.mapper;
import com.wudl.db.model.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @ClassName : UserMapper
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:03
*/
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wudl.db.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.wudl.db.model.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>
<sql id="Base_Column_List">
id, name
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.wudl.db.model.User">
insert into t_user (id, name)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.wudl.db.model.User">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.wudl.db.model.User">
update t_user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.wudl.db.model.User">
update t_user
set name = #{name,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
package com.wudl.db;
import com.wudl.db.model.User;
import com.wudl.db.service.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* @ClassName : Application
* @Description :
* @Author :wudl
* @Date: 2021-08-05 22:53
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ac= SpringApplication.run(Application.class, args);
UserService service= (UserService) ac.getBean("userService");
}
}
package com.wudl.db.controller;
import com.wudl.db.model.User;
import com.wudl.db.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName : UserController
* @Description :
* @Author :wudl
* @Date: 2021-08-06 00:38
*/
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/getUser")
public Object getUser()
{
List<User> users = userService.selectAllMaster();
List<User> users1 = userService.selectAllSlave();
Map<String ,Object> map= new HashMap<>();
map.put("master",users);
map.put("slave",users1);
return map;
}
}
#配置自定义数据库连接连接主库3307
master.datasource.driver-class-name=com.mysql.jdbc.Driver
master.datasource.url=jdbc:mysql://192.168.1.180:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
master.datasource.username=root
master.datasource.password=123456
#配置自定义数据库连接连接从库3309
slave.datasource.driver-class-name=com.mysql.jdbc.Driver
slave.datasource.url=jdbc:mysql://192.168.1.133:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
slave.datasource.username=root
slave.datasource.password=123456
网友评论