微框架spring boot

什么是spring boot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

为什么要使用spring boot

Spring IO大量的XML配置以及复杂的依赖管理一直是其饱受非议的一点。而Boot的实现不仅仅实现了免XML配置的开发体验,而且在一些场景中甚至不需要编写繁琐的import语句。Spring Boot的目标不在于为已解决的问题域提供新的解决方案,而是为平台带来另一种开发体验,从而简化对这些已有技术的使用。对于已经熟悉Spring生态系统的开发人员来说,Boot是一个很理想的选择,不过对于采用Spring技术的新人来说,Boot提供一种更简洁的方式来使用这些技术。

使用Spring Boot

要进行打包和分发的工程会依赖于像MavenGradle这样的构建系统。为了简化依赖图,Boot的功能是模块化的,通过导入Boot所谓的“starter”模块,可以将许多的依赖添加到工程之中。官方网站给我们提供了集成相关服务的项目例子,我们直接下载https://start.spring.io/
微框架spring boot
为了更容易地管理依赖版本和使用默认配置,框架提供了一个parent POM,工程可以继承它。Spring Boot工程的样例POM文件定义如下所示:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.   
  6.     <groupId>com.example</groupId>  
  7.     <artifactId>demo</artifactId>  
  8.     <version>0.0.2-SNAPSHOT</version>  
  9.     <!-- Boot默认打包为jar -->  
  10.     <packaging>war</packaging>  
  11.   
  12.     <name>demo</name>  
  13.     <description>Demo project for Spring Boot</description>  
  14.   
  15.     <parent>  
  16.         <groupId>org.springframework.boot</groupId>  
  17.         <artifactId>spring-boot-starter-parent</artifactId>  
  18.         <version>1.5.4.RELEASE</version>  
  19.         <relativePath/> <!-- lookup parent from repository -->  
  20.     </parent>  
  21.   
  22.     <properties>  
  23.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  24.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  25.         <java.version>1.8</java.version>  
  26.     </properties>  
  27.   
  28.     <dependencies>  
  29.         <dependency>  
  30.             <groupId>org.springframework.boot</groupId>  
  31.             <artifactId>spring-boot-starter-web-services</artifactId>  
  32.         </dependency>  
  33.   
  34.         <dependency>  
  35.             <groupId>org.springframework.boot</groupId>  
  36.             <artifactId>spring-boot-starter-web</artifactId>  
  37.         </dependency>  
  38.         <!-- 这里指定打包的时候不再需要tomcat相关的包 -->  
  39.         <dependency>  
  40.             <groupId>org.springframework.boot</groupId>  
  41.             <artifactId>spring-boot-starter-tomcat</artifactId>  
  42.             <!-- 打包时需要添加以下依赖 -->  
  43.             <!--<scope>provided</scope>-->  
  44.         </dependency>  
  45.   
  46.         <dependency>  
  47.             <groupId>org.springframework.boot</groupId>  
  48.             <artifactId>spring-boot-starter-test</artifactId>  
  49.             <scope>test</scope>  
  50.         </dependency>  
  51.         <!-- Spring Boot JDBC -->  
  52.         <dependency>  
  53.             <groupId>org.springframework.boot</groupId>  
  54.             <artifactId>spring-boot-starter-jdbc</artifactId>  
  55.         </dependency>  
  56.         <!-- 热部署 -->  
  57.         <dependency>  
  58.             <groupId>org.springframework.boot</groupId>  
  59.             <artifactId>spring-boot-devtools</artifactId>  
  60.             <!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 -->  
  61.             <optional>true</optional>  
  62.         </dependency>  
  63.         <!--整合cxf-->  
  64.         <dependency>  
  65.             <groupId>org.apache.cxf</groupId>  
  66.             <artifactId>cxf-rt-frontend-jaxws</artifactId>  
  67.             <version>3.1.6</version>  
  68.         </dependency>  
  69.         <dependency>  
  70.             <groupId>org.apache.cxf</groupId>  
  71.             <artifactId>cxf-rt-transports-http</artifactId>  
  72.             <version>3.1.6</version>  
  73.         </dependency>  
  74.         <!-- HikariCP依赖 -->  
  75.         <dependency>  
  76.             <groupId>com.zaxxer</groupId>  
  77.             <artifactId>HikariCP</artifactId>  
  78.             <!-- 版本号可以不用指定,Spring Boot会选用合适的版本 -->  
  79.         </dependency>  
  80.         <!-- mybatis-->  
  81.         <dependency>  
  82.             <groupId>org.mybatis.spring.boot</groupId>  
  83.             <artifactId>mybatis-spring-boot-starter</artifactId>  
  84.             <version>1.1.1</version>  
  85.         </dependency>  
  86.         <!-- 分页插件 -->  
  87.         <dependency>  
  88.             <groupId>com.github.pagehelper</groupId>  
  89.             <artifactId>pagehelper</artifactId>  
  90.             <version>4.1.0</version>  
  91.         </dependency>  
  92.         <!-- httpclient -->  
  93.         <dependency>  
  94.             <groupId>org.apache.httpcomponents</groupId>  
  95.             <artifactId>httpclient</artifactId>  
  96.             <version>4.1.2</version>  
  97.         </dependency>  
  98.         <dependency>  
  99.             <groupId>org.apache.httpcomponents</groupId>  
  100.             <artifactId>httpclient-cache</artifactId>  
  101.             <version>4.1.2</version>  
  102.         </dependency>  
  103.         <dependency>  
  104.             <groupId>org.apache.httpcomponents</groupId>  
  105.             <artifactId>httpmime</artifactId>  
  106.             <version>4.1.2</version>  
  107.         </dependency>  
  108.         <!-- json-lib-->  
  109.         <dependency>  
  110.             <groupId>net.sf.json-lib</groupId>  
  111.             <artifactId>json-lib</artifactId>  
  112.             <version>2.4</version>  
  113.             <classifier>jdk15</classifier>  
  114.         </dependency>  
  115.         <!-- 加入静态文件和jsp -->  
  116.         <!--对jsp的支持-->  
  117.         <dependency>  
  118.             <groupId>org.apache.tomcat.embed</groupId>  
  119.             <artifactId>tomcat-embed-jasper</artifactId>  
  120.             <!-- 打包时需要添加以下依赖 -->  
  121.             <!--<scope>provided</scope>-->  
  122.         </dependency>  
  123.         <!--配置servlet-->  
  124.         <dependency>  
  125.             <groupId>javax.servlet</groupId>  
  126.             <artifactId>javax.servlet-api</artifactId>  
  127.         </dependency>  
  128.         <dependency>  
  129.             <groupId>javax.servlet</groupId>  
  130.             <artifactId>jstl</artifactId>  
  131.         </dependency>  
  132.         <!-- MYSQL -->  
  133.         <dependency>  
  134.             <groupId>mysql</groupId>  
  135.             <artifactId>mysql-connector-java</artifactId>  
  136.             <version>5.1.7</version>  
  137.             <scope>system</scope>  
  138.             <systemPath>${basedir}/src/lib/mysql-connector-java-5.1.7-bin.jar</systemPath>  
  139.         </dependency>  
  140.         <!--添加外部依赖-->  
  141.         <dependency>  
  142.             <groupId>Ice</groupId>  
  143.             <artifactId>Ice</artifactId>  
  144.             <version>1.0</version>  
  145.             <scope>system</scope>  
  146.             <systemPath>${basedir}/src/lib/jsonrpc4j-0.27.jar</systemPath>  
  147.         </dependency>  
  148.         <!--<!– https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api –>-->  
  149.         <!--<dependency>-->  
  150.         <!--<groupId>javax.xml.bind</groupId>-->  
  151.         <!--<artifactId>jaxb-api</artifactId>-->  
  152.         <!--<version>2.2.11</version>-->  
  153.         <!--</dependency>-->  
  154.     </dependencies>  
  155.     <build>  
  156.         <plugins>  
  157.             <plugin>  
  158.                 <groupId>org.springframework.boot</groupId>  
  159.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  160.             </plugin>  
  161.             <!-- 打包跳过测试 -->  
  162.             <plugin>  
  163.                 <groupId>org.apache.maven.plugins</groupId>  
  164.                 <artifactId>maven-surefire-plugin</artifactId>  
  165.                 <configuration>  
  166.                     <skip>true</skip>  
  167.                 </configuration>  
  168.             </plugin>  
  169.             <!-- maven打包的时候告诉maven不需要web.xml,否刚会报找不到web.xml错误 -->  
  170.             <plugin>  
  171.                 <groupId>org.apache.maven.plugins</groupId>  
  172.                 <artifactId>maven-war-plugin</artifactId>  
  173.                 <version>2.4</version>  
  174.                 <configuration>  
  175.                     <failOnMissingWebXml>false</failOnMissingWebXml>  
  176.                     <!-- 将外部依赖打入war包的lib目录下 -->  
  177.                     <webResources>  
  178.                         <resource>  
  179.                             <directory>src/lib</directory>  
  180.                             <targetPath>WEB-INF/lib/</targetPath>  
  181.                             <includes>  
  182.                                 <include>**/*.jar</include>  
  183.                             </includes>  
  184.                         </resource>  
  185.                     </webResources>  
  186.                 </configuration>  
  187.             </plugin>  
  188.         </plugins>  
  189.         <!-- 手工设置resource -->  
  190.         <resources>  
  191.             <resource>  
  192.                 <directory>src/main/java</directory>  
  193.                 <includes>  
  194.                     <include>**/*</include>  
  195.                 </includes>  
  196.             </resource>  
  197.             <resource>  
  198.                 <directory>src/main/resources</directory>  
  199.                 <includes>  
  200.                     <include>**/*</include>  
  201.                 </includes>  
  202.             </resource>  
  203.             <resource>  
  204.                 <directory>src/main/webapp</directory>  
  205.                 <includes>  
  206.                     <include>**/*</include>  
  207.                 </includes>  
  208.             </resource>  
  209.         </resources>  
  210.     </build>  
  211. </project>  

构建Boot web应用
1.在配置文件中引入Spring Boot的web依赖:
[html] view plain copy
  1. <dependency>  
  2.            <groupId>org.springframework.boot</groupId>  
  3.            <artifactId>spring-boot-starter-web</artifactId>  
  4.        </dependency>  
spring-boot-starter-web  包含了很多内容,spring-webmvc、spring-web、jackson、validation、tomcat、starter。
2.开始编写代码,由于Maven默认编译路径为 src/main/java 下面的源码,所以,默认设置下,需要创建一些文件夹。
编写文件src\main\java\com\example\hello\HelloController.java:
[html] view plain copy
  1. package com.example.hello;  
  2.   
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. import org.springframework.web.bind.annotation.RequestParam;  
  5. import org.springframework.web.bind.annotation.RestController;  
  6.   
  7. import java.util.Map;  
  8. import java.util.ArrayList;  
  9. import java.util.HashMap;  
  10. import java.util.List;  
  11.   
  12. /**  
  13.  * Created by wuhaochao on 2017/7/12.  
  14.  */  
  15. @RestController  
  16. @RequestMapping("/hello")  
  17. public class HelloController {  
  18.     @RequestMapping("/index")  
  19.     public String index(@RequestParam String name) {  
  20. //        return "hello word" + name;  
  21.         return "index";  
  22.     }  
  23.   
  24.     @RequestMapping("/info")  
  25.     public Map<String, String> getInfo(@RequestParam String name) {  
  26.         Map<String, String> map = new HashMap<>();  
  27.         map.put("name", name);  
  28.         return map;  
  29.     }  
  30.   
  31.     @RequestMapping("/list")  
  32.     public List<Map<String, String>> getList() {  
  33.         List<Map<String, String>> list = new ArrayList<>();  
  34.         Map<String, String> map = null;  
  35.         for (int i = 1; i <= 5; i++) {  
  36.             map = new HashMap<>();  
  37.             map.put("name", "Shanhy-" + i);  
  38.             list.add(map);  
  39.         }  
  40.         return list;  
  41.     }  
  42. }  

@RestController因为我们例子是写一个web应用,因此写的这个注解,这个注解相当于同时添加@Controller@ResponseBody注解。

创建一个Application类:

[html] view plain copy
  1. package com.example;  
  2.   
  3. import org.apache.cxf.transport.servlet.CXFServlet;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.boot.builder.SpringApplicationBuilder;  
  7. import org.springframework.boot.web.servlet.ServletComponentScan;  
  8. import org.springframework.boot.web.servlet.ServletRegistrationBean;  
  9. import org.springframework.boot.web.support.SpringBootServletInitializer;  
  10. import org.springframework.context.annotation.Bean;  
  11. import org.springframework.scheduling.annotation.EnableAsync;  
  12. import org.springframework.scheduling.annotation.EnableScheduling;  
  13. import org.springframework.transaction.PlatformTransactionManager;  
  14. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  15. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;  
  16. import org.springframework.web.servlet.DispatcherServlet;  
  17.   
  18. //@EnableScheduling//启动定时探测  
  19. @EnableAsync//启动自定义线程池  
  20. @EnableTransactionManagement//启动事物管理  
  21. @SpringBootApplication  
  22. public class DemoApplication extends SpringBootServletInitializer {  
  23.     @Override  
  24.     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
  25.         return application.sources(DemoApplication.class);  
  26.     }  
  27.   
  28.     @Bean  
  29.     public ServletRegistrationBean restServlet() {  
  30.         //注解扫描上下文  
  31.         AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();  
  32.         // base package 这里指定到controller不指定*,因为配置有定时任务,容易造成bean冲突,导致定时任务执行2次  
  33.         applicationContext.scan("com.example.controller");  
  34.         // /通过构造函数指定dispatcherServlet的上下文  
  35.         DispatcherServlet rest_dispatcherServlet = new DispatcherServlet(applicationContext);  
  36.         // 用ServletRegistrationBean包装servlet  
  37.         ServletRegistrationBean registrationBean = new ServletRegistrationBean(rest_dispatcherServlet);  
  38.         registrationBean.setLoadOnStartup(1);  
  39.         //指定urlmapping  
  40.         registrationBean.addUrlMappings("/webapp/*");  
  41.         // 指定name,如果不指定默认为dispatcherServlet  
  42.         registrationBean.setName("webapp");  
  43.         return registrationBean;  
  44.     }  
  45.   
  46.     @Bean  
  47.     public Object testBean(PlatformTransactionManager platformTransactionManager) {  
  48.         System.out.println(">>>>>>>>>>>>>>>>>" + platformTransactionManager.getClass().getName() + "<<<<<<<<<<<<<<<<<<<<<");  
  49.         return new Object();  
  50.     }  
  51.   
  52.     public static void main(String[] args) {  
  53.         SpringApplication.run(DemoApplication.class, args);  
  54.     }  
  55.   
  56. }<strong>  
  57. </strong>  

注意Spring Boot建议将我们main方法所在的这个主要的配置类配置在根包src名下。

继承SpringBootServletIntializer和方法configure是后期为实现跳转前端页面的配置。

启动项目就可以在浏览器访问了。

数据访问
在配置文件application.properties中配置数据源:

[html] view plain copy
  1. #数据源设置  
  2. spring.datasource.url=jdbc:mysql://localhost:3306/stu_info  
  3. spring.datasource.username=root  
  4. spring.datasource.password=111111  
  5. spring.datasource.driver-class-name=com.mysql.jdbc.Driver  
  6.   
  7. spring.datasource.max-idle=10  
  8. #指定连接池等待连接返回的最大等待时间,毫秒单位.  
  9. spring.datasource.max-wait=10000  
  10. #指定必须保持连接的最小值  
  11. spring.datasource.min-idle=5  
  12. #指定连接池中最大的活跃连接数.  
  13. spring.datasource.secondary.max-active=50  
  14. spring.datasource.initial-size=5  
  15. spring.datasource.validation-query=SELECT 1  
  16. spring.datasource.test-on-borrow=false  
  17. spring.datasource.test-while-idle=true  
  18. spring.datasource.time-between-eviction-runs-millis=18800  
  19. spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)  
  20.   
  21. #mybatis数据文件路径  
  22. mybatis.mapper-locations=com/example/mapper/sql/*Mapper.xml  
  23. mybatis.type-aliases-package=com.example.entity  
添加mybatis相关依赖:

[html] view plain copy
  1. <!-- mybatis-->  
  2.         <dependency>  
  3.             <groupId>org.mybatis.spring.boot</groupId>  
  4.             <artifactId>mybatis-spring-boot-starter</artifactId>  
  5.             <version>1.1.1</version>  
  6.         </dependency>  
  7.         <!-- 分页插件 -->  
  8.         <dependency>  
  9.             <groupId>com.github.pagehelper</groupId>  
  10.             <artifactId>pagehelper</artifactId>  
  11.             <version>4.1.0</version>  
  12.         </dependency>  
编写mybatis:

[html] view plain copy
  1. package com.example.mapper;  
  2.   
  3. import com.example.entity.TranscationBean;  
  4. import org.apache.ibatis.annotations.Mapper;  
  5. import org.apache.ibatis.annotations.Param;  
  6.   
  7. import java.util.List;  
  8.   
  9. /**  
  10.  * Created by wuhaochao on 2017/7/24.  
  11.  */  
  12. @Mapper  
  13. public interface TranscationMapper {  
  14.     //    获取交易信息  
  15.     List<TranscationBean> getTranscation();  
  16.   
  17.     //    插入交易信息  
  18.     int insertTranscationBean(@Param("transcationBean") TranscationBean transcationBean);  
  19.   
  20.     //    批量插入交易信息  
  21.     int insertTranscationList(@Param("transcationList") List<TranscationBean> transcationList);  
  22. }  
对于的xml文件:

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.example.mapper.TranscationMapper">  
  5.   
  6.     <!-- type为实体类TranscationBean,包名已经配置,可以直接写类名 -->  
  7.     <resultMap id="transcationMap" type="TranscationBean">  
  8.         <id property="hash" column="transactionHash"/>  
  9.         <result property="transactionIndex" column="transactionIndex"/>  
  10.         <result property="blockHash" column="blockHash"/>  
  11.         <result property="blockNumber" column="blockNumber"/>  
  12.         <result property="from" column="from"/>  
  13.         <result property="to" column="to"/>  
  14.         <result property="nonce" column="nonce"/>  
  15.         <result property="gasPrice" column="gasPrice"/>  
  16.         <result property="gas" column="gas"/>  
  17.         <result property="input" column="input"/>  
  18.         <result property="value" column="value"/>  
  19.         <result property="timestamp" column="timestamp"/>  
  20.     </resultMap>  
  21.     <!-- 查询最新交易信息 -->  
  22.     <select id="getTranscation" resultMap="transcationMap" resultType="TranscationBean">  
  23.         select * from transaction_info t order by t.TIMESTAMP desc  
  24.     </select>  
  25.     <!-- 批量插入交易信息 -->  
  26.     <insert id="insertTranscationList" parameterType="java.util.List">  
  27.         insert into transaction_info VALUES  
  28.         <foreach collection="transcationList" item="trsList" index="index" open="(" close=")" separator=",">  
  29.             #{trsList.hash},#{trsList.transactionIndex},#{trsList.blockHash},  
  30.             #{trsList.blockNumber},#{trsList.from},#{trsList.to},  
  31.             #{trsList.nonce},#{trsList.gasPrice},#{trsList.gas},  
  32.             #{trsList.input},#{trsList.value},#{trsList.timestamp}  
  33.         </foreach>  
  34.     </insert>  
  35.     <!-- 插入交易信息 -->  
  36.     <insert id="insertTranscation" parameterType="TranscationBean">  
  37.         insert into transaction_info VALUES(  
  38.             #{hash},#{transactionIndex},#{blockHash},  
  39.             #{blockNumber},#{from},#{to},  
  40.             #{nonce},#{gasPrice},#{gas},  
  41.             #{input},#{value},#{timestamp}  
  42.             )  
  43.     </insert>  
  44. </mapper>  
配置mybatis分页插件:

[html] view plain copy
  1. package com.example.mapper;  
  2.   
  3. import com.github.pagehelper.PageHelper;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6. import org.springframework.context.annotation.Bean;  
  7. import org.springframework.context.annotation.Configuration;  
  8.   
  9. import java.util.Properties;  
  10.   
  11. /**  
  12.  * Created by wuhaochao on 2017/7/21.  
  13.  */  
  14. @Configuration  
  15. public class MyBatisConfiguration {  
  16.     private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);  
  17.   
  18.     @Bean  
  19.     public PageHelper geHelper() {  
  20.         logger.info("注册mybatis分页插件");  
  21.         PageHelper pageHelper = new PageHelper();  
  22.         Properties properties = new Properties();  
  23.         properties.setProperty("offsetAsPageNum", "true");  
  24.         properties.setProperty("rowBoundsWithCount", "true");  
  25.         properties.setProperty("reasonable", "true");  
  26.         pageHelper.setProperties(properties);  
  27.         return pageHelper;  
  28.     }  
  29. }  
控制层调用:

[html] view plain copy
  1. package com.example.controller;  
  2.   
  3. import com.example.entity.TranscationBean;  
  4. import com.example.mapper.TranscationMapper;  
  5. import com.example.unitl.Until;  
  6. import com.fasterxml.jackson.databind.ObjectMapper;  
  7. import com.github.pagehelper.PageHelper;  
  8. import com.github.pagehelper.PageInfo;  
  9. import net.sf.json.JSONArray;  
  10. import net.sf.json.JSONObject;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.web.bind.annotation.PathVariable;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.bind.annotation.RequestParam;  
  15. import org.springframework.web.bind.annotation.RestController;  
  16.   
  17. import java.util.ArrayList;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20.   
  21. /**  
  22.  * Created by wuhaochao on 2017/7/21.  
  23.  */  
  24.   
  25. /**  
  26.  * 交易  
  27.  */  
  28. @RequestMapping("/transcation")  
  29. @RestController  
  30. public class TranscationController {  
  31.     @Autowired  
  32.     private TranscationMapper transcationMapper;  
  33.   
  34.     /**  
  35.      * 获取全部交易信息  
  36.      *  
  37.      * @return  
  38.      * @throws Throwable  
  39.      */  
  40.     @RequestMapping("/getTransInfo")  
  41.     public Object getTranscationInfo() throws Throwable {  
  42.         List<TranscationBean> list = transcationMapper.getTranscation();  
  43.         return list;  
  44.     }  
  45.   
  46.     /**  
  47.      * 分页获取交易信息  
  48.      *  
  49.      * @param pagesize  
  50.      * @return  
  51.      * @throws Throwable  
  52.      */  
  53.     @RequestMapping("/getTransInfo/{pagesize}")  
  54.     public Object getTranscationInfoByPage(@PathVariable("pagesize") Integer pagesize) throws Throwable {  
  55.         PageHelper.startPage(1, pagesize);  
  56.         List<TranscationBean> list = transcationMapper.getTranscation();  
  57.         return new PageInfo(list);  
  58.     }  
  59.   
  60. }  
定时任务
Spring Boot定时任务相对Spring quartz来说更简单。
定义一个定时任务:

[html] view plain copy
  1. package com.example.Scheduled;  
  2.   
  3. /**  
  4.  * Created by wuhaochao on 2017/7/21.  
  5.  */  
  6.   
  7. import com.example.mapper.BlockMapper;  
  8. import com.example.mapper.TranscationMapper;  
  9. import com.example.theadPoolConfig.AsyncTranscationTask;  
  10. import com.example.unitl.Until;  
  11. import org.slf4j.Logger;  
  12. import org.slf4j.LoggerFactory;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.scheduling.annotation.Scheduled;  
  15. import org.springframework.stereotype.Component;  
  16. import org.springframework.transaction.annotation.Transactional;  
  17.   
  18. /**  
  19.  * 定时任务,每五秒探测一次区块链中的是否存在最新交易信息  
  20.  */  
  21. @Component  
  22. public class MyScheduled {  
  23.     private static final Logger logger = LoggerFactory.getLogger(MyScheduled.class);  
  24.     @Autowired  
  25.     private AsyncTranscationTask asyncTranscationTask;  
  26.     @Autowired  
  27.     private BlockMapper blockMapper;  
  28.   
  29.     /*每天每5秒执行一次*/  
  30.     @Scheduled(cron = "0/5 * * * * ?")  
  31.     @Transactional  
  32.     public void executeTask2() {  
  33.         //        获取最新区块编号  
  34.         try {  
  35.             int blockNumberNew = Integer.parseInt(  
  36.                     Until.encodeHexTodecimal(Until.JSONRPCClient(new Object[]{},  
  37.                             "eth_blockNumber").toString()));  
  38. //          查询数据库中存储的最新区块数据  
  39.             int blockNumberDataSource = blockMapper.getBlockNum();  
  40.             for (int i = blockNumberDataSource + 1; i <= blockNumberNew; i++) {  
  41.                 asyncTranscationTask.insertTransTask(i);  
  42.             }  
  43.         } catch (Throwable throwable) {  
  44.             throwable.printStackTrace();  
  45.         }  
  46.     }  
  47. }  
@Scheduled注解定义了定时任务
启动程序中需要加上@EnableScheduling注解启动定时任务探测。
多线程
Spring Boot有自己默认的线程池,这里我们自定义一个自己的线程池。
配置线程池:
[html] view plain copy
  1. package com.example.theadPoolConfig;  
  2.   
  3. /**  
  4.  * Created by wuhaochao on 2017/7/25.  
  5.  */  
  6.   
  7. import org.springframework.context.annotation.Bean;  
  8. import org.springframework.context.annotation.Configuration;  
  9. import org.springframework.scheduling.annotation.EnableAsync;  
  10. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  11.   
  12. import java.util.concurrent.Executor;  
  13. import java.util.concurrent.ThreadPoolExecutor;  
  14.   
  15. /**  
  16.  * 创建自定义线程池  
  17.  */  
  18. @Configuration  
  19. @EnableAsync  
  20. public class TaskExecutePool {  
  21.     @Bean  
  22.     public Executor myTaskAsyncPool() {  
  23.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
  24.         executor.setCorePoolSize(10);  
  25.         executor.setMaxPoolSize(50);  
  26.         executor.setQueueCapacity(1000);  
  27.         executor.setKeepAliveSeconds(300);  
  28.   
  29.         // rejection-policy:当pool已经达到max size的时候,如何处理新任务  
  30.         // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行  
  31.         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());  
  32.         executor.initialize();  
  33.         return executor;  
  34.   
  35.     }  
  36. }  
@EnableAsync注解并发。
使用自定义线程池:
[html] view plain copy
  1. package com.example.theadPoolConfig;  
  2.   
  3. import com.example.entity.BlockInfoBean;  
  4. import com.example.entity.TranscationBean;  
  5. import com.example.mapper.BlockMapper;  
  6. import com.example.mapper.TranscationMapper;  
  7. import com.example.unitl.Until;  
  8. import net.sf.json.JSONArray;  
  9. import net.sf.json.JSONObject;  
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.scheduling.annotation.Async;  
  14. import org.springframework.stereotype.Component;  
  15.   
  16. import java.util.ArrayList;  
  17. import java.util.List;  
  18.   
  19. /**  
  20.  * Created by wuhaochao on 2017/7/25.  
  21.  */  
  22. @Component  
  23. public class AsyncTranscationTask {  
  24.     private static final Logger logger = LoggerFactory.getLogger(AsyncTranscationTask.class);  
  25.     @Autowired  
  26.     private TranscationMapper transcationMapper;  
  27.     @Autowired  
  28.     private BlockMapper blockMapper;  
  29.   
  30.     //myTaskAsynPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池  
  31.     @Async("myTaskAsyncPool")  
  32.     public void insertTransTask(int i) throws InterruptedException {  
  33.         logger.info("TranscationTask" + i + " started.");  
  34.         //开始导入交易信息  
  35.         String method_BlockByNumber = "eth_getBlockByNumber";  
  36.         JSONObject objects = null;  
  37.         List<TranscationBean> list = null;  
  38.         JSONObject transtionObject = null;  
  39.         TranscationBean transcation = null;  
  40.         try {  
  41.             objects = JSONObject.fromObject(Until.JSONRPCClient(new Object[]{i, true}, method_BlockByNumber));  
  42.         } catch (Throwable throwable) {  
  43.             throwable.printStackTrace();  
  44.         }  
  45.         //插入区块信息  
  46.         BlockInfoBean blockInfoBean = new BlockInfoBean(objects);  
  47.         blockMapper.insertBlockInfo(blockInfoBean);  
  48.         if (JSONArray  
  49.                 .fromObject(objects.get("transactions")).size() > 0) {  
  50.             list = new ArrayList<TranscationBean>();  
  51.             for (java.util.Iterator tor = JSONArray  
  52.                     .fromObject(objects.get("transactions"))  
  53.                     .iterator(); tor.hasNext(); ) {  
  54.                 transtionObject = (JSONObject) tor.next();  
  55.                 transcation = new TranscationBean(transtionObject);  
  56.                 transcation.setTimestamp(Until.formatTimeMillis(objects.get("timestamp").toString()));  
  57.                 list.add(transcation);  
  58.             }  
  59.             //批量插入  
  60.             transcationMapper.insertTranscationList(list);  
  61.         }  
  62.     }  
  63.   
  64. }  
启动程序中需要加上@EnableAsync注解启动自定义线程池。
部署
Spring Boot默认打包为jar,按照官方文档操作即可,这里我们打包为war包,可以与前台静态页面交互的web应用。
POM文配置:

[html] view plain copy
  1. <!-- 加入静态文件和jsp -->  
  2.         <!--对jsp的支持-->  
  3.         <dependency>  
  4.             <groupId>org.apache.tomcat.embed</groupId>  
  5.             <artifactId>tomcat-embed-jasper</artifactId>  
  6.             <!-- 打包时需要添加以下依赖 -->  
  7.             <!--<scope>provided</scope>-->  
  8.         </dependency>  
  9.         <!--配置servlet-->  
  10.         <dependency>  
  11.             <groupId>javax.servlet</groupId>  
  12.             <artifactId>javax.servlet-api</artifactId>  
  13.         </dependency>  
  14.         <dependency>  
  15.             <groupId>javax.servlet</groupId>  
  16.             <artifactId>jstl</artifactId>  
  17.         </dependency>  
[html] view plain copy
  1. <!-- 这里指定打包的时候不再需要tomcat相关的包 -->  
  2.         <dependency>  
  3.             <groupId>org.springframework.boot</groupId>  
  4.             <artifactId>spring-boot-starter-tomcat</artifactId>  
  5.             <!-- 打包时需要添加以下依赖 -->  
  6.             <!--<scope>provided</scope>-->  
  7.         </dependency>  
[html] view plain copy
  1. <!-- 手工设置resource -->  
  2.         <resources>  
  3.             <resource>  
  4.                 <directory>src/main/java</directory>  
  5.                 <includes>  
  6.                     <include>**/*</include>  
  7.                 </includes>  
  8.             </resource>  
  9.             <resource>  
  10.                 <directory>src/main/resources</directory>  
  11.                 <includes>  
  12.                     <include>**/*</include>  
  13.                 </includes>  
  14.             </resource>  
  15.             <resource>  
  16.                 <directory>src/main/webapp</directory>  
  17.                 <includes>  
  18.                     <include>**/*</include>  
  19.                 </includes>  
  20.             </resource>  
  21.         </resources>  
[html] view plain copy
  1. <!-- 打包跳过测试 -->  
  2.             <plugin>  
  3.                 <groupId>org.apache.maven.plugins</groupId>  
  4.                 <artifactId>maven-surefire-plugin</artifactId>  
  5.                 <configuration>  
  6.                     <skip>true</skip>  
  7.                 </configuration>  
  8.             </plugin>  
  9.             <!-- maven打包的时候告诉maven不需要web.xml,否刚会报找不到web.xml错误 -->  
  10.             <plugin>  
  11.                 <groupId>org.apache.maven.plugins</groupId>  
  12.                 <artifactId>maven-war-plugin</artifactId>  
  13.                 <version>2.4</version>  
  14.                 <configuration>  
  15.                     <failOnMissingWebXml>false</failOnMissingWebXml>  
  16.                     <!-- 将外部依赖打入war包的lib目录下 -->  
  17.                     <webResources>  
  18.                         <resource>  
  19.                             <directory>src/lib</directory>  
  20.                             <targetPath>WEB-INF/lib/</targetPath>  
  21.                             <includes>  
  22.                                 <include>**/*.jar</include>  
  23.                             </includes>  
  24.                         </resource>  
  25.                     </webResources>  
  26.                 </configuration>  
  27.             </plugin>  
添加本地jar:

[html] view plain copy
  1. <!--添加外部依赖-->  
  2.         <dependency>  
  3.             <groupId>Ice</groupId>  
  4.             <artifactId>Ice</artifactId>  
  5.             <version>1.0</version>  
  6.             <scope>system</scope>  
  7.             <systemPath>${basedir}/src/lib/jsonrpc4j-0.27.jar</systemPath>  
  8.         </dependency>  

上一篇:SpringBoot 404问题汇总


下一篇:技术周刊2020-09-07