Spring Boot学习笔记(二)——集成MySQL及dubbo

版权声明:本文为博主原创文章,如需转载请注明出处,谢谢。 https://blog.csdn.net/zhouxingxingzxy/article/details/85914010

目录

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)  

猜你喜欢

转载自blog.csdn.net/zhouxingxingzxy/article/details/85914010