springboot2.0+mybatis多数据源集成
最近在学springboot,把学的记录下来。主要有springboot2.0+mybatis多数据源集成,logback日志集成,springboot单元测试。
一、代码结构如下
二、pom.xml文件如下
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 5 <groupId>spring-boot-2</groupId> 6 <artifactId>spring-boot-2</artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 <packaging>jar</packaging> 9 10 <name>spring-boot-2</name> 11 <url>http://maven.apache.org</url> 12 13 <properties> 14 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 15 </properties> 16 17 <dependencies> 18 <!-- spring boot依赖 --> 19 <dependency> 20 <groupId>org.springframework.boot</groupId> 21 <artifactId>spring-boot-starter-web</artifactId> 22 <version>2.0.3.RELEASE</version> 23 </dependency> 24 25 <!-- spring boot测试 --> 26 <dependency> 27 <groupId>org.springframework.boot</groupId> 28 <artifactId>spring-boot-starter-test</artifactId> 29 <version>2.0.3.RELEASE</version> 30 <scope>test</scope> 31 </dependency> 32 33 <!-- spring boot热启动 --> 34 <dependency> 35 <groupId>org.springframework.boot</groupId> 36 <artifactId>spring-boot-devtools</artifactId> 37 <optional>true</optional> 38 <version>2.0.3.RELEASE</version> 39 </dependency> 40 41 <!-- mysql --> 42 <dependency> 43 <groupId>mysql</groupId> 44 <artifactId>mysql-connector-java</artifactId> 45 <version>5.1.38</version> 46 </dependency> 47 48 <!-- mybatis --> 49 <dependency> 50 <groupId>org.mybatis.spring.boot</groupId> 51 <artifactId>mybatis-spring-boot-starter</artifactId> 52 <version>1.3.2</version> 53 </dependency> 54 55 <!-- alibaba的druid数据库连接池 --> 56 <dependency> 57 <groupId>com.alibaba</groupId> 58 <artifactId>druid-spring-boot-starter</artifactId> 59 <version>1.1.9</version> 60 </dependency> 61 </dependencies> 62 63 <build> 64 <plugins> 65 <!-- 规避检查src/main/webapp/WEB-INF下没有web.xml文件 --> 66 <plugin> 67 <groupId>org.apache.maven.plugins</groupId> 68 <artifactId>maven-war-plugin</artifactId> 69 <version>2.3</version> 70 <configuration> 71 <failOnMissingWebXml>false</failOnMissingWebXml> 72 </configuration> 73 </plugin> 74 <!-- maven热启动 --> 75 <plugin> 76 <groupId>org.springframework.boot</groupId> 77 <artifactId>spring-boot-maven-plugin</artifactId> 78 <configuration> 79 <fork>true</fork> 80 </configuration> 81 </plugin> 82 <!-- 跳过单元测试 --> 83 <plugin> 84 <groupId>org.apache.maven.plugins</groupId> 85 <artifactId>maven-surefire-plugin</artifactId> 86 <configuration> 87 <skip>true</skip> 88 </configuration> 89 </plugin> 90 91 <!-- 指定jdk版本 --> 92 <plugin> 93 <groupId>org.apache.maven.plugins</groupId> 94 <artifactId>maven-compiler-plugin</artifactId> 95 <configuration> 96 <source>1.8</source> 97 <target>1.8</target> 98 </configuration> 99 </plugin> 100 </plugins> 101 </build> 102 </project>
三、编写application.yml文件,springboot支持properties和yml两种格式的配置文件,我使用的是yml文件。使用yml文件需要注意的是只支持空格,不支持tab等,可以下个eclipse的yml插件。
配置文件如下
1 # 数据源 2 spring: 3 datasource: 4 # master数据源配置 5 master: 6 driverClassName: com.mysql.jdbc.Driver 7 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 8 username: root 9 password: root 10 # cluster数据源配置 11 cluster: 12 driverClassName: com.mysql.jdbc.Driver 13 url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8 14 username: root 15 password: root 16
四、编写主从库的配置代码,代码差不多一样,只不过主库配置类的方法上需要加@Primary注解,用来告诉spring默认使用这个配置,主库配置类代码如下
1 package com.spring.boot.config; 2 3 4 import javax.sql.DataSource; 5 6 import org.apache.ibatis.session.SqlSessionFactory; 7 import org.mybatis.spring.SqlSessionFactoryBean; 8 import org.mybatis.spring.SqlSessionTemplate; 9 import org.mybatis.spring.annotation.MapperScan; 10 import org.springframework.beans.factory.annotation.Qualifier; 11 import org.springframework.boot.context.properties.ConfigurationProperties; 12 import org.springframework.boot.jdbc.DataSourceBuilder; 13 import org.springframework.context.annotation.Bean; 14 import org.springframework.context.annotation.Configuration; 15 import org.springframework.context.annotation.Primary; 16 import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 17 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 18 19 /** 20 * mysql从库配置类 21 * @日期: 2018年7月5日 下午10:05:25 22 * @作者: Chendb 23 */ 24 @Configuration 25 @MapperScan(basePackages = "com.spring.boot.master.mapper",sqlSessionTemplateRef = "masterSqlSessionTemplate") 26 public class MasterDataSourceConfig { 27 28 /** 29 * 创建数据源 30 *@return DataSource 31 */ 32 @Bean(name = "masterDataSource") 33 @ConfigurationProperties(prefix = "spring.datasource.master") 34 @Primary 35 public DataSource masterDataSource() { 36 return DataSourceBuilder.create().build(); 37 } 38 39 /** 40 * 创建工厂 41 *@param dataSource 42 *@throws Exception 43 *@return SqlSessionFactory 44 */ 45 @Bean(name = "masterSqlSessionFactory") 46 @Primary 47 public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception { 48 SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 49 bean.setDataSource(dataSource); 50 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml")); 51 return bean.getObject(); 52 } 53 54 /** 55 * 创建事务 56 *@param dataSource 57 *@return DataSourceTransactionManager 58 */ 59 @Bean(name = "masterTransactionManager") 60 @Primary 61 public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) { 62 return new DataSourceTransactionManager(dataSource); 63 } 64 65 /** 66 * 创建模板 67 *@param sqlSessionFactory 68 *@return SqlSessionTemplate 69 */ 70 @Bean(name = "masterSqlSessionTemplate") 71 @Primary 72 public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { 73 return new SqlSessionTemplate(sqlSessionFactory); 74 } 75 76 }
从库配置类代码如下
1 package com.spring.boot.config; 2 3 4 import javax.sql.DataSource; 5 6 import org.apache.ibatis.session.SqlSessionFactory; 7 import org.mybatis.spring.SqlSessionFactoryBean; 8 import org.mybatis.spring.SqlSessionTemplate; 9 import org.mybatis.spring.annotation.MapperScan; 10 import org.springframework.beans.factory.annotation.Qualifier; 11 import org.springframework.boot.context.properties.ConfigurationProperties; 12 import org.springframework.boot.jdbc.DataSourceBuilder; 13 import org.springframework.context.annotation.Bean; 14 import org.springframework.context.annotation.Configuration; 15 import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 16 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 17 18 /** 19 * mysql主库配置类 20 * @日期: 2018年7月5日 下午10:05:25 21 * @作者: Chendb 22 */ 23 @Configuration 24 @MapperScan(basePackages = "com.spring.boot.mapper.cluster",sqlSessionTemplateRef = "clusterSqlSessionTemplate") 25 public class ClusterDataSourceConfig { 26 27 /** 28 * 创建数据源 29 *@return DataSource 30 */ 31 @Bean(name = "clusterDataSource") 32 @ConfigurationProperties(prefix = "spring.datasource.cluster") 33 public DataSource masterDataSource() { 34 return DataSourceBuilder.create().build(); 35 } 36 37 /** 38 * 创建工厂 39 *@param dataSource 40 *@throws Exception 41 *@return SqlSessionFactory 42 */ 43 @Bean(name = "clusterSqlSessionFactory") 44 public SqlSessionFactory masterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource dataSource) throws Exception { 45 SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 46 bean.setDataSource(dataSource); 47 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/cluster/*.xml")); 48 return bean.getObject(); 49 } 50 51 /** 52 * 创建事务 53 *@param dataSource 54 *@return DataSourceTransactionManager 55 */ 56 @Bean(name = "clusterTransactionManager") 57 public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("clusterDataSource") DataSource dataSource) { 58 return new DataSourceTransactionManager(dataSource); 59 } 60 61 /** 62 * 创建模板 63 *@param sqlSessionFactory 64 *@return SqlSessionTemplate 65 */ 66 @Bean(name = "clusterSqlSessionTemplate") 67 public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("clusterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { 68 return new SqlSessionTemplate(sqlSessionFactory); 69 } 70 71 }
五、配置mybatis的mapper文件,主库的mapper文件如下
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.spring.boot.mapper.cluster.ClusterUserMapper" > 4 <!-- 结果映射 --> 5 <resultMap id="BaseMap" type="com.spring.boot.model.UserModel"> 6 <id column="userId" property="userId" jdbcType="INTEGER" /> 7 <result column="userName" property="userName" jdbcType="VARCHAR" /> 8 <result column="password" property="password" jdbcType="VARCHAR" /> 9 <result column="phone" property="phone" jdbcType="VARCHAR" /> 10 </resultMap> 11 12 <!-- 表所有字段 --> 13 <sql id="allColumns"> 14 userId, userName, password, phone 15 </sql> 16 17 <!-- 查询所有数据 --> 18 <select id="getAll" resultMap="BaseMap"> 19 SELECT 20 <include refid="allColumns" /> 21 FROM T_USER 22 </select> 23 24 <!-- 根据主键查询数据 --> 25 <select id="get" resultMap="BaseMap" parameterType="java.util.Map"> 26 SELECT 27 <include refid="allColumns" /> 28 FROM 29 t_user u 30 WHERE 31 1 = 1 32 AND userId = #{userId} 33 </select> 34 35 <!-- 插入数据 --> 36 <insert id="insert" parameterType="java.util.Map"> 37 <!--获取最新更新的主键--> 38 <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="userId"> 39 SELECT LAST_INSERT_ID() AS userId 40 </selectKey> 41 INSERT INTO T_USER (<include refid="allColumns" />) 42 VALUES ( 43 #{userId}, 44 #{userName}, 45 #{password}, 46 #{phone} 47 ) 48 </insert> 49 50 <!-- 修改数据 --> 51 <update id="update" parameterType="java.util.Map"> 52 UPDATE T_USER SET 53 userName = #{userName}, 54 PASSWORD = #{password}, 55 PHONE = #{phone} 56 WHERE userId = #{userId} 57 </update> 58 59 60 <!-- 根据主键删除数据 --> 61 <delete id="delete" parameterType="Integer"> 62 DELETE FROM T_USER WHERE userId = #{userId} 63 </delete> 64 65 </mapper>
从库的mapper文件如下
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.spring.boot.mapper.master.MasterUserMapper" > 4 <!-- 结果映射 --> 5 <resultMap id="BaseMap" type="com.spring.boot.model.UserModel"> 6 <id column="userId" property="userId" jdbcType="INTEGER" /> 7 <result column="userName" property="userName" jdbcType="VARCHAR" /> 8 <result column="password" property="password" jdbcType="VARCHAR" /> 9 <result column="phone" property="phone" jdbcType="VARCHAR" /> 10 </resultMap> 11 12 <!-- 表所有字段 --> 13 <sql id="allColumns"> 14 userId, userName, password, phone 15 </sql> 16 17 <!-- 查询所有数据 --> 18 <select id="getAll" resultMap="BaseMap"> 19 SELECT 20 <include refid="allColumns" /> 21 FROM T_USER 22 </select> 23 24 <!-- 根据主键查询数据 --> 25 <select id="get" resultMap="BaseMap" parameterType="java.util.Map"> 26 SELECT 27 <include refid="allColumns" /> 28 FROM 29 t_user u 30 WHERE 31 1 = 1 32 AND userid = #{userId} 33 </select> 34 35 <!-- 插入数据,返回主键 --> 36 <insert id="insert" parameterType="java.util.Map" useGeneratedKeys="true" keyProperty="userId" keyColumn="userId"> 37 INSERT INTO T_USER (userName,password,phone) 38 VALUES ( 39 #{userName}, 40 #{password}, 41 #{phone} 42 ) 43 </insert> 44 45 <!-- 修改数据 --> 46 <update id="update" parameterType="java.util.Map"> 47 UPDATE T_USER SET 48 userName = #{userName}, 49 PASSWORD = #{password}, 50 PHONE = #{phone} 51 WHERE userId = #{userId} 52 </update> 53 54 55 <!-- 根据主键删除数据 --> 56 <delete id="delete" parameterType="Integer"> 57 DELETE FROM T_USER WHERE userId = #{userId} 58 </delete> 59 60 </mapper>
六、编写mybatis的dao层,这里不需要编写具体的dao层实现,只写接口类,只要保证mapper配置文件的命名空间和接口类的全限定名一致并且接口方法名和mapper文件的sql标识符对应即可
主库的接口类如下
1 package com.spring.boot.mapper.master; 2 3 import java.util.List; 4 5 import com.spring.boot.model.UserModel; 6 7 public interface MasterUserMapper { 8 9 /** 10 * 获取全部用户数据 11 *@return List<UserModel> 用户列表 12 */ 13 List<UserModel> getAll(); 14 15 /** 16 * 获取用户数据 17 *@param userId 用户id 18 *@return UserModel 用户数据 19 */ 20 UserModel get(Integer userId); 21 22 /** 23 * 保存用户 24 *@param userModel 用户数据 25 *@return Integer 是否成功,1成功,0失败 26 */ 27 Integer insert(UserModel userModel); 28 29 /** 30 * 更新用户 31 *@param userModel 用户数据 32 *@return Integer 是否成功,1成功,0失败 33 */ 34 Integer update(UserModel userModel); 35 36 /** 37 * 删除用户 38 *@param userId 用户id 39 *@return Integer 是否成功,1成功,0失败 40 */ 41 Integer delete(Integer userId); 42 }
从库的接口类如下
1 package com.spring.boot.mapper.cluster; 2 3 import java.util.List; 4 5 import com.spring.boot.model.UserModel; 6 7 public interface ClusterUserMapper { 8 /** 9 * 获取全部用户数据 10 *@return List<UserModel> 用户列表 11 */ 12 List<UserModel> getAll(); 13 14 /** 15 * 获取用户数据 16 *@param userId 用户id 17 *@return UserModel 用户数据 18 */ 19 UserModel get(Integer userId); 20 21 /** 22 * 保存用户 23 *@param userModel 用户数据 24 *@return Integer 是否成功,1成功,0失败 25 */ 26 Integer insert(UserModel userModel); 27 28 /** 29 * 更新用户 30 *@param userModel 用户数据 31 *@return Integer 是否成功,1成功,0失败 32 */ 33 Integer update(UserModel userModel); 34 35 /** 36 * 删除用户 37 *@param userId 用户id 38 *@return Integer 是否成功,1成功,0失败 39 */ 40 Integer delete(Integer userId); 41 }
七、springboot启动类
1 package com.spring.boot; 2 3 import org.mybatis.spring.annotation.MapperScan; 4 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 7 /** 8 * springboot启动类 9 * @日期: 2018年7月5日 下午10:03:36 10 * @作者: Chendb 11 */ 12 @SpringBootApplication 13 @MapperScan("com.spring.boot.mapper") 14 public class Application { 15 16 public static void main(String[] args) { 17 SpringApplication.run(Application.class, args); 18 } 19 20 }
八、实体类和数据库表
1 package com.spring.boot.model; 2 3 import java.io.Serializable; 4 5 public class UserModel implements Serializable{ 6 /** 7 * 8 */ 9 private static final long serialVersionUID = 1L; 10 11 /** 12 * 用户id 13 */ 14 private Integer userId; 15 16 /** 17 * 用户名称 18 */ 19 private String userName; 20 21 /** 22 * 用户密码 23 */ 24 private String password; 25 26 /** 27 * 电话 28 */ 29 private String phone; 30 31 /** 32 * 获取用户id 33 *@return Integer 用户id 34 */ 35 public Integer getUserId() { 36 return userId; 37 } 38 39 /** 40 * 设置用户id 41 *@param userId 用户id 42 *@return void 43 */ 44 public void setUserId(Integer userId) { 45 this.userId = userId; 46 } 47 48 /** 49 * 获取用户名称 50 *@return String 用户名称 51 */ 52 public String getUserName() { 53 return userName; 54 } 55 56 /** 57 * 设置用户名称 58 *@param userName 用户名称 59 *@return void 60 */ 61 public void setUserName(String userName) { 62 this.userName = userName; 63 } 64 65 /** 66 * 获取用户密码 67 *@return String 用户密码 68 */ 69 public String getPassword() { 70 return password; 71 } 72 73 /** 74 * 设置用户密码 75 *@param password 用户密码 76 *@return void 77 */ 78 public void setPassword(String password) { 79 this.password = password; 80 } 81 82 /** 83 * 获取电话 84 *@return String 电话 85 */ 86 public String getPhone() { 87 return phone; 88 } 89 90 /** 91 * 设置电话 92 *@param phone 电话 93 *@return void 94 */ 95 public void setPhone(String phone) { 96 this.phone = phone; 97 } 98 }
1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : local 5 Source Server Version : 50713 6 Source Host : localhost:3306 7 Source Database : test2 8 9 Target Server Type : MYSQL 10 Target Server Version : 50713 11 File Encoding : 65001 12 13 Date: 2018-07-06 23:14:03 14 */ 15 16 SET FOREIGN_KEY_CHECKS=0; 17 18 -- ---------------------------- 19 -- Table structure for t_user 20 -- ---------------------------- 21 DROP TABLE IF EXISTS `t_user`; 22 CREATE TABLE `t_user` ( 23 `userId` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id', 24 `userName` varchar(255) NOT NULL COMMENT '用户名称', 25 `password` varchar(255) NOT NULL COMMENT '用户密码', 26 `phone` varchar(255) NOT NULL COMMENT '电话', 27 PRIMARY KEY (`userId`) 28 ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
九、控制层以及单元测试类
1 package com.spring.boot.controller; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RestController; 8 9 import com.spring.boot.mapper.cluster.ClusterUserMapper; 10 import com.spring.boot.mapper.master.MasterUserMapper; 11 import com.spring.boot.model.UserModel; 12 13 /** 14 * 用户控制层 15 * @日期: 2018年7月5日 下午11:18:04 16 * @作者: Chendb 17 */ 18 @RestController 19 public class UserController { 20 21 @Autowired 22 private MasterUserMapper masterUserMapper; 23 24 @Autowired 25 private ClusterUserMapper clusterUserMapper; 26 27 /************************主库控制层接口-start******************************/ 28 @RequestMapping("user/getAllMaster") 29 public List<UserModel> getAllMaster() { 30 return masterUserMapper.getAll(); 31 } 32 33 @RequestMapping("user/getMaster") 34 public UserModel getUserMaster(Integer userId) { 35 return masterUserMapper.get(userId); 36 } 37 38 @RequestMapping("user/insertMaster") 39 public Integer insertMaster(UserModel userModel) { 40 masterUserMapper.insert(userModel); 41 // 必须使用对象获取id,否则无法获取到主键,而是获取到0(插入失败)或者1(插入成功) 42 return userModel.getUserId(); 43 } 44 45 @RequestMapping("user/updateMaster") 46 public Integer updateMaster(UserModel userModel) { 47 return masterUserMapper.update(userModel); 48 } 49 50 @RequestMapping("user/deleteMaster") 51 public Integer deleteMaster(Integer userId) { 52 return masterUserMapper.delete(userId); 53 } 54 /************************主库控制层接口-end******************************/ 55 56 /************************从库控制层接口-start******************************/ 57 @RequestMapping("user/getAllCluster") 58 public List<UserModel> getAllCluster() { 59 return clusterUserMapper.getAll(); 60 } 61 62 @RequestMapping("user/getCluster") 63 public UserModel getUserCluster(Integer userId) { 64 return clusterUserMapper.get(userId); 65 } 66 67 @RequestMapping("user/insertCluster") 68 public Integer insertCluster(UserModel userModel) { 69 clusterUserMapper.insert(userModel); 70 // 必须使用对象获取id,否则无法获取到主键,而是获取到0(插入失败)或者1(插入成功) 71 return userModel.getUserId(); 72 } 73 74 @RequestMapping("user/updateCluster") 75 public Integer updateCluster(UserModel userModel) { 76 return clusterUserMapper.update(userModel); 77 } 78 79 @RequestMapping("user/deleteCluster") 80 public Integer deleteCluster(Integer userId) { 81 return clusterUserMapper.delete(userId); 82 } 83 /************************从库控制层接口-end******************************/ 84 }
1 package com.spring.boot; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.junit.runner.RunWith; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.boot.test.context.SpringBootTest; 8 import org.springframework.http.MediaType; 9 import org.springframework.test.context.junit4.SpringRunner; 10 import org.springframework.test.web.servlet.MockMvc; 11 import org.springframework.test.web.servlet.ResultActions; 12 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 13 import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 14 import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 import org.springframework.test.web.servlet.setup.MockMvcBuilders; 16 import org.springframework.web.context.WebApplicationContext; 17 18 @RunWith(SpringRunner.class) 19 @SpringBootTest 20 public class UserControllerTest { 21 22 @Autowired 23 private WebApplicationContext context; 24 25 private MockMvc mvc; 26 27 @Before 28 public void setUp() throws Exception { 29 this.mvc = MockMvcBuilders.webAppContextSetup(context).build(); 30 } 31 32 /************************主库控制层接口测试-start******************************/ 33 @Test 34 public void testInsertMaster() throws Exception { 35 ResultActions action = mvc.perform(MockMvcRequestBuilders 36 .post("/user/insertMaster") 37 .param("userName", "testName") 38 .param("password", "password") 39 .param("phone", "13578236975") 40 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 41 .accept(MediaType.APPLICATION_JSON)) 42 .andExpect(MockMvcResultMatchers.status().isOk()) 43 .andDo(MockMvcResultHandlers.print()); 44 String userId = action.andReturn().getResponse().getContentAsString(); 45 46 System.out.println("userId:" + userId); 47 } 48 49 @Test 50 public void testGetAllMaster() throws Exception { 51 52 // 先保存,确保有数据 53 mvc.perform(MockMvcRequestBuilders 54 .post("/user/insertMaster") 55 .param("userName", "testName") 56 .param("password", "password") 57 .param("phone", "13578236975") 58 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 59 .accept(MediaType.APPLICATION_JSON)) 60 .andExpect(MockMvcResultMatchers.status().isOk()) 61 .andDo(MockMvcResultHandlers.print()); 62 63 mvc.perform(MockMvcRequestBuilders 64 .get("/user/getAllMaster") 65 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 66 .accept(MediaType.APPLICATION_JSON)) 67 .andExpect(MockMvcResultMatchers.status().isOk()) 68 .andDo(MockMvcResultHandlers.print()); 69 } 70 71 @Test 72 public void testGetMaster() throws Exception { 73 // 先保存,确保有数据 74 ResultActions action = mvc.perform(MockMvcRequestBuilders 75 .post("/user/insertMaster") 76 .param("userName", "testName1") 77 .param("password", "password1") 78 .param("phone", "13578236975") 79 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 80 .accept(MediaType.APPLICATION_JSON)) 81 .andExpect(MockMvcResultMatchers.status().isOk()) 82 .andDo(MockMvcResultHandlers.print()); 83 84 String userId = action.andReturn().getResponse().getContentAsString(); 85 System.out.println("userId:" + userId); 86 87 mvc.perform(MockMvcRequestBuilders 88 .get("/user/getMaster") 89 .param("userId", userId) 90 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 91 .accept(MediaType.APPLICATION_JSON)) 92 .andExpect(MockMvcResultMatchers.status().isOk()) 93 .andDo(MockMvcResultHandlers.print()); 94 } 95 96 @Test 97 public void testUpdateMaster() throws Exception { 98 // 先保存,确保有数据 99 ResultActions action = mvc.perform(MockMvcRequestBuilders 100 .post("/user/insertMaster") 101 .param("userName", "testName1") 102 .param("password", "password1") 103 .param("phone", "13578236975") 104 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 105 .accept(MediaType.APPLICATION_JSON)) 106 .andExpect(MockMvcResultMatchers.status().isOk()) 107 .andDo(MockMvcResultHandlers.print()); 108 109 String userId = action.andReturn().getResponse().getContentAsString(); 110 System.out.println("userId:" + userId); 111 112 mvc.perform(MockMvcRequestBuilders 113 .post("/user/updateMaster") 114 .param("userName", "修改") 115 .param("password", "password") 116 .param("phone", "13578236975") 117 .param("userId", userId) 118 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 119 .accept(MediaType.APPLICATION_JSON)) 120 .andExpect(MockMvcResultMatchers.status().isOk()) 121 .andDo(MockMvcResultHandlers.print()); 122 } 123 124 @Test 125 public void testDeleteMaster() throws Exception { 126 127 // 先保存,确保有数据 128 ResultActions action = mvc.perform(MockMvcRequestBuilders 129 .post("/user/insertMaster") 130 .param("userName", "testName1") 131 .param("password", "password1") 132 .param("phone", "13578236975") 133 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 134 .accept(MediaType.APPLICATION_JSON)) 135 .andExpect(MockMvcResultMatchers.status().isOk()) 136 .andDo(MockMvcResultHandlers.print()); 137 138 String userId = action.andReturn().getResponse().getContentAsString(); 139 System.out.println("userId:" + userId); 140 141 mvc.perform(MockMvcRequestBuilders 142 .delete("/user/deleteMaster") 143 .param("userId", userId) 144 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 145 .accept(MediaType.APPLICATION_JSON)) 146 .andExpect(MockMvcResultMatchers.status().isOk()) 147 .andDo(MockMvcResultHandlers.print()); 148 } 149 /************************主库控制层接口测试-end******************************/ 150 151 /************************从库控制层接口测试-start******************************/ 152 153 @Test 154 public void testInsertCluster() throws Exception { 155 mvc.perform(MockMvcRequestBuilders 156 .post("/user/insertCluster") 157 .param("userName", "testName") 158 .param("password", "password") 159 .param("phone", "13578236975") 160 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 161 .accept(MediaType.APPLICATION_JSON)) 162 .andExpect(MockMvcResultMatchers.status().isOk()) 163 .andDo(MockMvcResultHandlers.print()); 164 } 165 166 @Test 167 public void testGetAllCluster() throws Exception { 168 // 先保存,确保有数据 169 ResultActions action = mvc.perform(MockMvcRequestBuilders 170 .post("/user/insertCluster") 171 .param("userName", "testName1") 172 .param("password", "password1") 173 .param("phone", "13578236975") 174 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 175 .accept(MediaType.APPLICATION_JSON)) 176 .andExpect(MockMvcResultMatchers.status().isOk()) 177 .andDo(MockMvcResultHandlers.print()); 178 179 String userId = action.andReturn().getResponse().getContentAsString(); 180 System.out.println("userId:" + userId); 181 182 mvc.perform(MockMvcRequestBuilders 183 .get("/user/getAllCluster") 184 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 185 .accept(MediaType.APPLICATION_JSON)) 186 .andExpect(MockMvcResultMatchers.status().isOk()) 187 .andDo(MockMvcResultHandlers.print()); 188 } 189 190 @Test 191 public void testGetCluster() throws Exception { 192 // 先保存,确保有数据 193 ResultActions action = mvc.perform(MockMvcRequestBuilders 194 .post("/user/insertCluster") 195 .param("userName", "testName1") 196 .param("password", "password1") 197 .param("phone", "13578236975") 198 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 199 .accept(MediaType.APPLICATION_JSON)) 200 .andExpect(MockMvcResultMatchers.status().isOk()) 201 .andDo(MockMvcResultHandlers.print()); 202 203 String userId = action.andReturn().getResponse().getContentAsString(); 204 System.out.println("userId:" + userId); 205 206 mvc.perform(MockMvcRequestBuilders 207 .get("/user/getCluster") 208 .param("userId", userId) 209 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 210 .accept(MediaType.APPLICATION_JSON)) 211 .andExpect(MockMvcResultMatchers.status().isOk()) 212 .andDo(MockMvcResultHandlers.print()); 213 } 214 215 @Test 216 public void testUpdateCluster() throws Exception { 217 // 先保存,确保有数据 218 ResultActions action = mvc.perform(MockMvcRequestBuilders 219 .post("/user/insertCluster") 220 .param("userName", "testName1") 221 .param("password", "password1") 222 .param("phone", "13578236975") 223 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 224 .accept(MediaType.APPLICATION_JSON)) 225 .andExpect(MockMvcResultMatchers.status().isOk()) 226 .andDo(MockMvcResultHandlers.print()); 227 228 String userId = action.andReturn().getResponse().getContentAsString(); 229 System.out.println("userId:" + userId); 230 231 mvc.perform(MockMvcRequestBuilders 232 .post("/user/updateCluster") 233 .param("userName", "testName修改") 234 .param("password", "password") 235 .param("phone", "13578236975") 236 .param("userId", userId) 237 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 238 .accept(MediaType.APPLICATION_JSON)) 239 .andExpect(MockMvcResultMatchers.status().isOk()) 240 .andDo(MockMvcResultHandlers.print()); 241 } 242 243 @Test 244 public void testDeleteCluster() throws Exception { 245 246 // 先保存,确保有数据 247 ResultActions action = mvc.perform(MockMvcRequestBuilders 248 .post("/user/insertCluster") 249 .param("userName", "testName1") 250 .param("password", "password1") 251 .param("phone", "13578236975") 252 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 253 .accept(MediaType.APPLICATION_JSON)) 254 .andExpect(MockMvcResultMatchers.status().isOk()) 255 .andDo(MockMvcResultHandlers.print()); 256 257 String userId = action.andReturn().getResponse().getContentAsString(); 258 System.out.println("userId:" + userId); 259 260 mvc.perform(MockMvcRequestBuilders 261 .delete("/user/deleteCluster") 262 .param("userId", userId) 263 .content(MediaType.APPLICATION_JSON_UTF8_VALUE) 264 .accept(MediaType.APPLICATION_JSON)) 265 .andExpect(MockMvcResultMatchers.status().isOk()) 266 .andDo(MockMvcResultHandlers.print()); 267 } 268 /************************从库控制层接口测试-end******************************/ 269 }
十、springboot已经包含了logback的相关jar包,只要在类路径下有名为“logback-spring”的xml文件即可进行日志打印,具体配置如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <configuration scan="true" scanPeriod="10 seconds"> 3 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 4 <encoder> 5 <!-- do not add line number output , it will slow down the execution speed --> 6 <pattern>%d{HH:mm:ss.SSS} [%thread] %level %logger{36} - %msg%n</pattern> 7 </encoder> 8 </appender> 9 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> 10 <!-- 按天来回滚,如果需要按小时来回滚,则设置为{yyyy-MM-dd_HH} --> 11 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 12 <!--文件路径和文件名称--> 13 <fileNamePattern>${catalina.base}/logs/test.%d{yyyy-MM-dd}.log</fileNamePattern> 14 <!-- 如果按天来回滚,则最大保存时间为1天,1天之前的都将被清理掉 --> 15 <maxHistory>30</maxHistory> 16 </rollingPolicy> 17 <!-- 日志输出格式 --> 18 <layout class="ch.qos.logback.classic.PatternLayout"> 19 <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n</Pattern> 20 </layout> 21 </appender> 22 <!-- 异步输出 --> 23 <!--输出文件--> 24 <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"> 25 <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 --> 26 <discardingThreshold>0</discardingThreshold> 27 <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 --> 28 <queueSize>512</queueSize> 29 <!-- 添加附加的appender,最多只能添加一个 --> 30 <appender-ref ref="FILE"/> 31 </appender> 32 <!--输出控制台--> 33 <appender name="ASYNC_STD" class="ch.qos.logback.classic.AsyncAppender"> 34 <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 --> 35 <discardingThreshold>0</discardingThreshold> 36 <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 --> 37 <queueSize>512</queueSize> 38 <!-- 添加附加的appender,最多只能添加一个 --> 39 <appender-ref ref="STDOUT"/> 40 </appender> 41 42 <root level="DEBUG"> 43 <!-- 输出到控制台 --> 44 <appender-ref ref="ASYNC_STD"/> 45 <!-- 输出到文件 --> 46 <!-- <appender-ref ref="ASYNC"/> --> 47 </root> 48 49 </configuration>
github地址:https://github.com/1053531172/springboot2
参考:http://www.ityouknow.com/springboot/2016/11/25/spring-boot-multi-mybatis.html