1. 程式人生 > >Spring Boot學習筆記(二)——整合MySQL及dubbo

Spring Boot學習筆記(二)——整合MySQL及dubbo

目錄

L 3.Spring Boot整合MySQL

一、使用JDBCTemplate引入MySQL

1.新增spring boot jdbc資料來源配置

2.引入maven依賴(jdbc、connector、druid)

二、整合mybatis

1.單資料來源mybatis整合

2.多資料來源mybatis整合

L 4.Spring Boot整合SuperDiamond

1.引入maven依賴

2.在啟動類中新增需要通過集中配置替換的檔案

L 5.Spring Boot整合Dubbo

1.引入Dubbo和註冊中心ZooKeeper的依賴

2.新增Dubbo Consumer的配置

3.在主類上新增dubbo 配置註解(程式碼段中標記黃色的部分)

4.在程式中使用依賴注入所需引用的服務


L 3.Spring Boot整合MySQL

Spring Boot可以有多種方式引入MySQL,總結知學寶採用的有兩種最常用的引入方式:1.使用jdbcTemplate方式引入MySQL2.使用Mybatis方式引入MySQL

一、使用JDBCTemplate引入MySQL

使用JDBCTemplate引入MySQL的整合步驟如下:

1.新增spring boot jdbc資料來源配置

	spring.datasource.test.driver-class-name=com.mysql.jdbc.Driver  
	spring.datasource.test.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8  
	spring.datasource.test.username=root  
	spring.datasource.test.password=  
	spring.datasource.test.type=com.alibaba.druid.pool.DruidDataSource  
	spring.datasource.test.initialSize=5  
	spring.datasource.test.maxActive=50  
	spring.datasource.test.minIdle=5  
	spring.datasource.test.maxIdle=15  
	spring.datasource.test.timesBetweenEvictionRunsMillis=600000  
	spring.datasource.test.minEvictableIdleTimeMillis=1800000  
	spring.datasource.test.testWhileIdle=true  
	spring.datasource.test.validationQuery=SELECT 1  

2.引入maven依賴(jdbc、connector、druid)

	<dependency>  
	    <groupId>org.springframework.boot</groupId>  
	    <artifactId>spring-boot-starter-jdbc</artifactId>  
	</dependency>  
	<dependency>  
	    <groupId>mysql</groupId>  
	    <artifactId>mysql-connector-java</artifactId>  
	    <scope>runtime</scope>  
	</dependency>  
	<dependency>  
	    <groupId>com.alibaba</groupId>  
	    <artifactId>druid</artifactId>  
	    <version>1.0.29</version>  
	</dependency> 

以上依賴分別引入了JDBCTemplate、聯結器以及連線池管理等元件,構成完整的MySQL使用環境。

使用jdbcTemplate即可編寫常用的DAO程式碼,如下所示:

	@Repository("bugFixDAO")  
	public class BugFixDAOImpl {  
	  
	    @Autowired  
	    private NamedParameterJdbcTemplate npJDBCTemplate;  
	  
	    /** 
	     * bugfix table name 
	     */  
	    private static final String BUG_FIX_TABLE = "bugfix";  
  
	    public List<BugFixRecord> findFixRecords(int count){  
	        StringBuilder sql = new StringBuilder();  
	        sql.append(" SELECT id,bugId,submitUserId,isFixed,extra FROM ").append(BUG_FIX_TABLE)  
	        .append(" ORDER BY id DESC limit :count;");  
	  
	        Map<String, Integer> param = new HashMap<String, Integer>();  
	        param.put("count", count);  
	  
	        List<BugFixRecord> recordList = npJDBCTemplate.query(sql.toString(), param, new BugFixRecordMapper());  
	        return recordList;  
	    }  
	}  

Service程式碼也沒有什麼區別:

@Service("bugFixService")
public class BugFixServiceImpl implements BugFixService {

    @Autowired
    private BugFixDAOImpl bugFixDAO;

    @Override
    public List<BugFixRecord> getBugFixRecords(Integer count) {

        return bugFixDAO.findFixRecords(count);
    }

    @Override
    public void addBugFixRecord(BugFixRecord fixRecord) {
        Assert.notNull(fixRecord, "fixRecord is required!");
        Assert.hasText(fixRecord.getBugId(), "bugId(property of fixRecord) is required!");
        bugFixDAO.insertRecord(fixRecord);
    }
}

Spring Boot使用JDBCTemplate整合MySQL時,其多資料來源的初始化方式與mybatis整合多資料來源類似,構建主資料來源及其他的資料來源,在使用的時候再DAO中注入需要的template bean即可。

二、整合mybatis

mybatis的資料來源配置和裸用jdbc的配置基本一致,只需要在application.properties裡再加上mapper.xml路徑的配置,同時配合mapper類上的註解@Mapper註解即可實現使用mybatis操作資料。

## mybatis
mybatis.mapper-locations=classpath:mapper/*/*_mapper.xml

引入spring boot mybatis依賴:

<!-- mybatis -->
<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>${mybatis-spring-boot-starter.version}</version>
</dependency>

1.單資料來源mybatis整合

單資料來源的資料來源的propertiesJDBCTemplate一致。通過該配置指定mapper.xml檔案的路徑後,專案啟動的時候spring boot元件會掃描指定的mapper.xml檔案以及mapper類。

mapper.xml檔案示例:

	<?xml version="1.0" encoding="UTF-8"?>  
	<!DOCTYPE mapper PUBLIC "-//com.order.test.org//DTD Mapper 3.0//EN"  
	        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
	<mapper namespace="com.example.demo.mybatis.test.mapper.XmlBugFixerMapper">  
	    <resultMap id="BugFixerMap" type="com.example.demo.domain.BugFixer">  
	        <!-- <id property="id" column="id"/> -->  
	        <result property="userId" column="userId"/>  
	        <result property="name" column="name"/>  
	        <result property="sexuality" column="sexuality"/>  
	        <result property="age" column="age"/>  
	        <result property="email" column="email"/>  
	        <result property="phone" column="phone"/>  
	        <!-- <result property="createTime" column="createTime"/>  
	        <result property="updateTime" column="updateTime"/> -->  
	    </resultMap>  
	    <sql id="COLUMN_LIST"> userId,name,sexuality,age,email,phone</sql>  
	    <sql id="FROM_TABLE"> FROM user</sql>  
	    <select id="findFixers" parameterType="java.lang.Integer" resultMap="BugFixerMap">  
	        SELECT  
	            <include refid="COLUMN_LIST"></include>  
	            <include refid="FROM_TABLE"></include>  
	        ORDER BY id DESC LIMIT #{startIndex},#{size};  
	    </select>  
	    <insert id="add" parameterType="com.example.demo.domain.BugFixer">  
	        INSERT INTO user (<include refid="COLUMN_LIST"></include>) VALUES  (#{fixer.userId,jdbcType=VARCHAR},#{fixer.name,jdbcType=VARCHAR},#{fixer.sexuality,jdbcType=VARCHAR},#{fixer.age,jdbcType=INTEGER},#{fixer.email,jdbcType=VARCHAR},#{fixer.phone,jdbcType=VARCHAR});  
	    </insert>  
	</mapper>  

結合相應的mapper類即可實現DAO層功能。

	@Mapper  
	public interface XmlBugFixerMapper {  
	  
	    List<BugFixer> findFixers(@Param("startIndex") Integer startIndex, @Param("size") Integer size);  
	  
	    /** 
	     * 新增一個fixer 
	     * @param fixer 
	     * <pre> 
	     * mybatis apper介面中使用Param標籤註解引數時,會覆蓋掉其mapper.xml檔案中的sql中的parameterType屬性的配置, 
	     * 此時取pojo物件中的屬性需使用fixer.userId的形式獲取屬性值。 
	     * 這種獲取方式主要是由於mybatis將入參會封裝成Map<k,v>,k為引數名稱,v為入參值 
	     * </pre> 
	     * @return 
	     */  
	    int add(@Param("fixer") BugFixer fixer);  
	}  

除使用mapper.xml檔案定義mappersql的方式外,我們還可以使用在mapper類的方法上使用註解的方式定義方法的sql語句,實現資料操作功能。

	@Mapper  
	public interface BugFixerMapper {  
	  
	    public static final String BASE_COLUMN_LIST = "userId,name,sexuality,age,email,phone";  
	  
	    @Insert("INSERT INTO user (userId,name,sexuality,age,email,phone) VALUES (#{userId},#{name},#{sexuality},#{age},#{email},#{phone});")  
	    int add(@Param("userId") String userId, @Param("name") String name, @Param("sexuality") String sex, @Param("age") int age,@Param("email") String email, @Param("phone") String phone);  
	  
	    @Select("SELECT " + BASE_COLUMN_LIST + " FROM user ORDER BY id DESC LIMIT #{startIndex},#{size}")
            List<BugFixer> findFixers(@Param("startIndex") int startIndex, @Param("size") int size);  
	} 

2.多資料來源mybatis整合

spring boot 使用多資料來源的方式整合mybatis時,無法使用spring bootmybatis預設的方式初始化資料來源,因此需要開發者自己編寫每個資料來源的配置類,實現多資料來源的初始化。

多資料來源的資料來源的基本屬性的配置有一個坑,即其資料庫的url配置與單資料來源下有所不同,需要加上“jdbc-”,不然無法正常初始化資料來源。

	# SQL CONFIG START #  
	## JDBC  
	spring.datasource.test.driver-class-name=com.mysql.jdbc.Driver  
	spring.datasource.test.jdbc-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8  
	spring.datasource.test.username=root  
	spring.datasource.test.password=  
	spring.datasource.test.type=com.alibaba.druid.pool.DruidDataSource  
	spring.datasource.test.initialSize=5  
	spring.datasource.test.maxActive=50  
	spring.datasource.test.minIdle=5  
	spring.datasource.test.maxIdle=15  
	spring.datasource.test.timesBetweenEvictionRunsMillis=600000  
	spring.datasource.test.minEvictableIdleTimeMillis=1800000  
	spring.datasource.test.testWhileIdle=true  
	spring.datasource.test.validationQuery=SELECT 1  
	  
	spring.datasource.student.jdbc-url=jdbc:mysql://test.mysql.zhixue.com:3306/student_test?useUnicode=true&characterEncoding=UTF-8  
	spring.datasource.student.username=${jdbc.username.student}  
	spring.datasource.student.password=${jdbc.password.student}  
	spring.datasource.student.driver-class-name=${jdbc.driver.student} 

手動配置資料來源的方式主要初始化步驟為:

    1)建立dataSource

    2)建立SqlSessionFactory

   3)建立SqlSessionTemplate

   4)需要的話,可以建立事務管理器DataSourceTransactionManager

需要注意的是,在配置多資料來源的時候需要制定其中某一個數據源作為主資料來源,只需要在上述的建立資料來源例項時在資料來源的各個功能例項上新增@Primary註解即可。

具體實現例項如下:

a.設定DataSource

	/** 
	 * 配置資料來源 
	 */  
	@Configuration  
	public class DataSourceConfig {  
	  
	    @Bean("testDataSource")  
	    @ConfigurationProperties(prefix="spring.datasource.test")  
	    @Primary  
	    public DataSource testDataSource(){  
	        return DataSourceBuilder.create().build();  
	    }  
  
	    @Bean("studentDataSource")  
	    @ConfigurationProperties(prefix="spring.datasource.student")  
	    public DataSource studentDataSource(){  
	        return DataSourceBuilder.create().build();  
	    }  
	}

b.設定各資料來源的SqlSessionFactorySqlSessionTemplateDataSourceTransactionManager

主資料來源 testDatasource

	@Configuration  
	@MapperScan(basePackages = {"com.example.demo.mybatis.test"},sqlSessionFactoryRef="testSqlSessionFactory")  
	public class DBTestMybatisConfig {  
	  
	    @Bean(name="testSqlSessionFactory")  
	    @Primary  
	    public SqlSessionFactory sqlSessionFactoryTest(@Qualifier("testDataSource") DataSource dataSource) throws Exception {  
	        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();  
	        // 使用test資料來源, 連線test庫  
	        factoryBean.setDataSource(dataSource);  
	        return factoryBean.getObject();  
	    }  
	  
	    @Bean(name = "testTransactionManager")  
	    @Primary  
	    public DataSourceTransactionManager testTransactionManager(@Qualifier("testDataSource") DataSource dataSource) {  
	        return new DataSourceTransactionManager(dataSource);  
	    }  
	  
	    @Bean(name="testSqlSessionTemplate")  
	    @Primary  
	    public SqlSessionTemplate sqlSessionTemplateTest(@Qualifier("testSqlSessionFactory") SqlSessionFactory testSqlSessionFactory) throws Exception {  
	        // 使用上面配置的Factory  
	        SqlSessionTemplate template = new SqlSessionTemplate(testSqlSessionFactory);  
	        return template;  
	    }  
	}

其他資料來源 studentDataSource

	@Configuration  
	@MapperScan(basePackages = {"com.example.demo.mybatis.student"}, sqlSessionFactoryRef="studentSqlSessionFactory")  
	public class DBStudentMybatisConfig {  
	  
	    @Bean("studentSqlSessionFactory")  
	    public SqlSessionFactory sqlSessionFactoryStudent(@Qualifier("studentDataSource") DataSource stuDataSource) throws Exception{  
	        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();  
	        factoryBean.setDataSource(stuDataSource);  
	        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/student/*.xml"));  
	        return factoryBean.getObject();  
	    }  
	  
	    @Bean("studentTransactionManager")  
	    public DataSourceTransactionManager studentTransactionManager(@Qualifier("studentDataSource") DataSource stuDataSource){  
	        return new DataSourceTransactionManager(stuDataSource);  
	    }  
	  
	    @Bean("studentSqlSessionTemplate")  
	    public SqlSessionTemplate sqlSessionTemplateStudent(@Qualifier("studentSqlSessionFactory") SqlSessionFactory studentSqlSessionFactory) throws Exception {  
	        SqlSessionTemplate template = new SqlSessionTemplate(studentSqlSessionFactory);  
	        return template;  
	    }  
	}  

以上建立資料來源時需要指定資料來源作用範圍,即哪些mapper使用該資料來源進行資料操作,未指定資料來源的mapper將使用主資料來源完成資料操作。


L 4.Spring Boot整合SuperDiamond

開發部署過程中往往同樣的配置在不同的環境中使用的配置值是不一樣的,因此我們需要整合集中的配置系統管理、使用專案中的配置。目前智學主要使用的SuperDiamond實現這一功能;而在Spring Boot專案中整合SuperDiamond也比較簡單,具體步驟如下:

1.引入maven依賴

<dependency>  
    <groupId>com.github.diamond</groupId>  
    <artifactId>super-diamond-client</artifactId>  
    <version>${super-diamond-client.version}</version>  
</dependency>  

2.在啟動類中新增需要通過集中配置替換的檔案

	public class DemoApplication {  
	  
	    public static void main(String[] args) {  
	        PropertiesConfiguration configuration = new PropertiesConfiguration();  
	        configuration.filterConfig("application.properties");  
	        SpringApplication.run(DemoApplication.class, args);  
	    }  
	}

在專案啟動類的main方法中加入標記中的兩行程式碼即可實現通過集中配置初始不同環境下的配置項。


L 5.Spring Boot整合Dubbo

Spring Boot專案中整合Dubbo與通常的Spring專案基本類似,只是在配置方式上有一定區別。在Spring Boot中整合Dubbo的步驟如下:

1.引入Dubbo和註冊中心ZooKeeper的依賴

	<dependency>  
	    <groupId>com.alibaba.spring.boot</groupId>  
	    <artifactId>dubbo-spring-boot-starter</artifactId>  
	    <version>${dubbo-spring-boot.version}</version>  
	</dependency>  
	          
	<dependency>  
	    <groupId>com.github.sgroschupf</groupId>  
	    <artifactId>zkclient</artifactId>  
	    <version>0.1</version>  
	</dependency> 

2.新增Dubbo Consumer的配置

	# DUBBO CONFIG START #  
	## dubbo consumer  
	spring.dubbo.application.name=spring-boot-dubbo-consumer  
	spring.dubbo.registry.address=zookeeper://192.168.159.148:2181?backup=192.168.57.191:2181,192.168.157.238:2181,192.168.159.187:2181,192.168.159.188:2181
	spring.dubbo.scan=com.iflytek.edu.zx.bizservice.study.service.activity.RenewalActivityService  
	spring.dubbo.consumer.timeout=3000  
	spring.dubbo.consumer.check=false  
	spring.dubbo.consumer.retries=0  
	# DUBBO CONFIG END #

3.在主類上新增dubbo 配置註解(程式碼段中標記黃色的部分)

	@SpringBootApplication  
	@EnableDubboConfiguration  
	public class DemoApplication {  
	  
	    public static void main(String[] args) {  
	        PropertiesConfiguration configuration = new PropertiesConfiguration();  
	        configuration.filterConfig("application.properties");  
	        SpringApplication.run(DemoApplication.class, args);  
	    }  
	}

4.在程式中使用依賴注入所需引用的服務

    @RequestMapping("/activity")  
    @RestController  
    public class ActivityController {
	  
	    @Reference
	    private RenewalActivityService renewActivityService;  
	  
	    @RequestMapping(value="/vipStatistics",method={RequestMethod.GET, RequestMethod.POST})  
	    public RenewVIPstatisticsDTO getVipStatistics(@RequestParam String userId){  
	        Assert.hasText(userId, "userId is required!");  
	        return renewActivityService.getRenewVIPstatisticsDTO(userId);  
        }
    }

經過以上4步即可實現在spring boot專案中使用dubbo實現遠端的服務呼叫功能。

Dubbo Consumer配置需要注意以下幾點:

1zk地址的解析與使用xml檔案配置的地址解析方式不一致,所以zk叢集地址的設定方式也有一定區別:

spring boot application.properties檔案中zk地址如下:zookeeper://192.168.159.148:2181?backup=192.168.157.91:2181,192.168.157.238:2181,192.168.159.187:2181,192.168.159.188:2181  

spring dubbo_consuemr.xml檔案中的zk叢集地址如下: zookeeper://192.168.159.148:2181,192.168.157.91:2181,192.168.157.238:2181,192.168.159.187:2181,192.168.159.188:2181  

2service依賴設定方式

通過配置“spring.dubbo.scan=服務類路徑”來設定依賴的服務

3)依賴服務在消費程式碼中的依賴注入所使用的註解不同

通常bean注入都可使用@Autowired註解完成,但是spring boot中在bean中注入dubbo服務的話需要使用@Reference註解。

使用Autowired註解會報以下錯誤:

	***************************  
	APPLICATION FAILED TO START  
	***************************  
	  
	Description:  
	  
	Field renewActivityService in com.example.demo.controller.ActivityController required a bean of type 'com.iflytek.edu.zx.bizservice.study.service.activity.RenewalActivityService' that could not be found.  
	  
	The injection point has the following annotations:  
	    - @org.springframework.beans.factory.annotation.Autowired(required=true)