1. 程式人生 > >SpringBoot實現多數據源(實戰源碼)

SpringBoot實現多數據源(實戰源碼)

tsql insert jdbc turn 學習 location 1.3 reat ssl

  通過一個數據庫的表數據去查詢同步另一個數據庫,之前的方式是通過寫個小工具,然後jdbc方式進行處理,這個方式也挺好用的.學習了springboot後發現可以實現多數據源操作,然後就具體實現以下.

以下代碼主要實現的功能有mysql數據的增刪改查,oracle數據庫的查,還有將mysql數據同步到oracle中.

代碼目錄結構

java/com.fxust
+config
  -FirstDBConfig.java
  -SecondConfig.java
+controller
  -NoteController.java
  -UserController.java
+dao
  +first
    -UserMapper.java


  +second
    -NoteMapper.java
+model
  +first
    -User.java
  +second
    -Note.java
+service
  +impl
    -NoteServiceImpl.java
    -UserServiceImpl.java
  -NoteService.java
  -UserService.java
-BootApplication
resources
  -application.yml

pom.xml文件的配置情況

技術分享圖片
<?xml version="1.0" encoding="UTF-8"?>
<
project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fxust</groupId> <artifactId>
boot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>boot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
View Code

application.yml配置,springboot支持原生的yml配置

server:
  port: 8088 //配置啟動的端口
//配置mysql數據源
firstDataSource:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=true
  username: root
  password: root
//配置oracle數據源
secondDataSource:
  driver-class-name: oracle.jdbc.driver.OracleDriver
  url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
  username: test
  password: test

通過代碼獲取配置數據源

package com.fxust.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Created by fgq on 2017/12/28.
 */
@Configuration
@MapperScan(basePackages = "com.fxust.dao.first",sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDBConfig {

    @Bean(name = "firstDataSource")
    @ConfigurationProperties(prefix = "firstDataSource")
    public DataSource firstDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "firstSqlSessionFactory")
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }
}
package com.fxust.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Created by fgq on 2017/12/28.
 */
@Configuration
@MapperScan(basePackages = "com.fxust.dao.second",sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDBConfig {


    @Bean(name = "secondDataSource")
    @ConfigurationProperties(prefix = "secondDataSource")
    @Primary
    public DataSource secondDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondSqlSessionFactory")
    @Primary
    public SqlSessionFactory secondSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }
}

基於註解實現dao層的增刪改查

package com.fxust.dao.first;

import com.fxust.model.first.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Created by fgq on 2017/12/28.
 */

@Mapper
public interface UserMapper {

    @Select("select * from user where id = #{id}")
    User queryById(@Param("id") int id);

    @Select("select * from user")
    List<User> queryAll();

    @Insert({"insert into user(id,name,age,hobby)values(#{id},#{name},#{age},#{hobby})"})
    int add(User user);

    @Update("update user set name=#{name},age=#{age},hobby=#{hobby} where id=#{id}")
    int update(User user);

    @Delete("delete from user where id=#{id}")
    int delete(int id);
}
package com.fxust.dao.second;

import com.fxust.model.second.Note;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Created by fgq on 2017/12/28.
 */
@Mapper
public interface NoteMapper {

    @Select("select human_id humanId,human_name humanName,human_age humanAge,human_hobby humanHobby,insert_time insertTime from NOTE order by insert_time desc")
    List<Note> queryAll();

    @Insert("insert into note(human_id,human_name,human_age,human_hobby)values(#{humanId},#{humanName},#{humanAge},#{humanHobby})")
    void insert(Note note);
}

model層代碼

public class User {
    private String id;

    private String name;

    private String age;

    private String hobby;
  //省略setter,getter方法  
}
public class Note {

    private int humanId;

    private String humanName;

    private int humanAge;

    private String humanHobby;

    private String insertTime;
 //省略setter,getter方法  
}

service層實現業務邏輯

技術分享圖片
package com.fxust.service.impl;

import com.fxust.dao.first.UserMapper;
import com.fxust.dao.second.NoteMapper;
import com.fxust.model.first.User;
import com.fxust.model.second.Note;
import com.fxust.service.UserSerivce;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by fgq on 2018/1/12.
 */
@Service
public class UserServiceImpl implements UserSerivce {

    @Autowired
    UserMapper userDao;

    @Autowired
    NoteMapper noteDao;

    public User queryById(int id){
        return userDao.queryById(id);
    }

    public PageInfo<User> queryAllUser(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userDao.queryAll();
        return new PageInfo<>(userList);
    }

    public String addUser(User user){
        return userDao.add(user) == 1 ? "success" : "fail";
    }

    public String updateUser(User user){
        return userDao.update(user) == 1 ? "success" : "fail";
    }

    public String deleteUser(int id){
        return userDao.delete(id) == 1 ? "success" : "fail";
    }

    public void synMysqlToOracle() {
        List<User> userList = userDao.queryAll();
        for (User user : userList) {
            Note note = new Note();
            String userId = user.getId();
            String userName = user.getName();
            String userAge = user.getAge();
            String userHobby = user.getHobby();
            note.setHumanId(Integer.valueOf(userId));
            note.setHumanName(userName);
            note.setHumanAge(Integer.valueOf(userAge));
            note.setHumanHobby(userHobby);
            noteDao.insert(note);
        }
    }
}
View Code 技術分享圖片
package com.fxust.service.impl;

import com.fxust.dao.second.NoteMapper;
import com.fxust.model.second.Note;
import com.fxust.service.NoteService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by fgq on 2018/1/12.
 */
@Service
public class NoteServiceImpl implements NoteService {

    @Autowired
    NoteMapper noteDao;

    public PageInfo<Note> queryAllNote(int pageNum,int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Note> noteList =  noteDao.queryAll();
        return new PageInfo<>(noteList);
    }
}
View Code

controller層實現接口訪問控制

技術分享圖片
package com.fxust.controller;

import com.fxust.model.second.Note;
import com.fxust.service.NoteService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by fgq on 2017/12/28.
 */
@Controller
@RequestMapping("/note")
public class NoteController {

    @Autowired
    NoteService noteService;

    //@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize
    @RequestMapping("queryAll")
    @ResponseBody
    PageInfo<Note> queryAll(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return noteService.queryAllNote(pageNum, pageSize);
    }
}
View Code 技術分享圖片
package com.fxust.controller;

import com.fxust.model.first.User;
import com.fxust.service.UserSerivce;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by fengguoqiang on 2017/12/28.
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    UserSerivce userSerivce;

    @RequestMapping(value = "/queryById")
    @ResponseBody
    User queryById(int id){
        return userSerivce.queryById(id);
    }

    @RequestMapping(value = "/queryAll")
    @ResponseBody
    PageInfo<User> queryAll(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                            @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        return userSerivce.queryAllUser(pageNum, pageSize);
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    String addUser(User user){
       return userSerivce.addUser(user);
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    String updateUser(User user){
        return userSerivce.updateUser(user);
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    String delete(int id){
        return userSerivce.deleteUser(id);
    }

    @RequestMapping(value = "/syn")
    @ResponseBody
    void synData(){
        userSerivce.synMysqlToOracle();//應該在系統啟動後異步執行
    }

}
View Code

調用接口如下

/user/add?name=biadu&age=12&hobby=web

/user/update?name=yahu&age=33&hobby=web&id=2

/user/queryById?id=2

/user/delete?id=1

/user/queryAll

/note/queryAll

SpringBoot實現多數據源(實戰源碼)