博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring cloud task Demo搭建
阅读量:6844 次
发布时间:2019-06-26

本文共 13594 字,大约阅读时间需要 45 分钟。

起步:什么是 spring cloud task

Spring Cloud Task makes it easy to create short lived microservices. We provide capabilities that allow short lived JVM processes to be executed on demand in a production environment.

Spring Cloud Task 是为了实现短生命周期的、定时执行的、不需要被重新启动的轻量级应用架构。

创建 Demo

demo 已发布 可以下载参考

1.首先需要创建一个 springBoot 项目

2.除此以外需要加入数据库依赖,Spring Cloud Task 支持主流数据库(H2、HSQLDB、MySql、Oracle、Postgres)我们以mysql为例

org.springframework.boot
spring-boot-starter-data-jpa
1.5.7.RELEASE
mysql
mysql-connector-java

3.引入task依赖

org.springframework.cloud
spring-cloud-task-core
1.0.0.BUILD-SNAPSHOT

4.在application.properties中配置数据库信息

#DB Configuration:spring.datasource.driverClassName=com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/testdbspring.datasource.username = rootspring.datasource.password = root#JPA Configuration:spring.jpa.database=MySQLspring.jpa.show-sql=true  spring.jpa.generate-ddl=true  spring.jpa.hibernate.ddl-auto=update#spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialectspring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy  #spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MYSQL5Dialect

5.编写你的Application

@SpringBootApplication@EnableTaskpublic class SpringCloudTaskApplication {    public static void main(String[] args) {        SpringApplication.run(SpringCloudTaskApplication.class, args);    }    @Bean    public CommandLineRunner commandLineRunner() {        return new TestCommandLineRunner();    }    public static class TestCommandLineRunner implements CommandLineRunner {        @Override        public void run(String... strings) throws Exception {            System.out.println("this is a Test about spring cloud task.");            try{                List
list = new ArrayList<>(); list.get(1); }catch (Exception e){ System.out.println("Error"); throw e; } } }}

注意: 以上代码中通过异常的形式故意通过list.get(1)抛出,便于在数据库中可以看到一些数据产生。

6.现在可以通过运行main方法启动你的demo,以下是控制台输出:

.   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.5.7.RELEASE)2017-09-25 17:02:43.349  INFO 11592 --- [           main] c.x.s.SpringCloudTaskApplication         : Starting SpringCloudTaskApplication on XinLing with PID 11592 (D:\workspaces\Java\spring-cloud-task\target\classes started by theem in D:\workspaces\Java\spring-cloud-task)2017-09-25 17:02:43.351  INFO 11592 --- [           main] c.x.s.SpringCloudTaskApplication         : No active profile set, falling back to default profiles: default2017-09-25 17:02:43.383  INFO 11592 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@11c20519: startup date [Mon Sep 25 17:02:43 CST 2017]; root of context hierarchy2017-09-25 17:02:43.938  INFO 11592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'2017-09-25 17:02:43.947  INFO 11592 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [    name: default    ...]2017-09-25 17:02:43.988  INFO 11592 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}2017-09-25 17:02:43.989  INFO 11592 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found2017-09-25 17:02:43.989  INFO 11592 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist2017-09-25 17:02:44.016  INFO 11592 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.Mon Sep 25 17:02:44 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.2017-09-25 17:02:44.307  INFO 11592 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect2017-09-25 17:02:44.406  INFO 11592 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update2017-09-25 17:02:44.422  INFO 11592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'2017-09-25 17:02:44.514  INFO 11592 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/cloud/task/schema-mysql.sql]2017-09-25 17:02:44.532  INFO 11592 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/cloud/task/schema-mysql.sql] in 17 ms.2017-09-25 17:02:44.636  INFO 11592 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup2017-09-25 17:02:44.640  INFO 11592 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0this is a Test about spring cloud task.Error2017-09-25 17:02:44.675  INFO 11592 --- [           main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.2017-09-25 17:02:44.687  INFO 11592 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@11c20519: startup date [Mon Sep 25 17:02:43 CST 2017]; root of context hierarchy2017-09-25 17:02:44.688  INFO 11592 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 02017-09-25 17:02:44.689  INFO 11592 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown2017-09-25 17:02:44.689  INFO 11592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'2017-09-25 17:02:44.698 ERROR 11592 --- [           main] o.s.boot.SpringApplication               : Application startup failedjava.lang.IllegalStateException: Failed to execute CommandLineRunner    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at com.xz.springCoudTask.SpringCloudTaskApplication.main(SpringCloudTaskApplication.java:17) [classes/:na]Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0    at java.util.ArrayList.rangeCheck(ArrayList.java:653) ~[na:1.8.0_91]    at java.util.ArrayList.get(ArrayList.java:429) ~[na:1.8.0_91]    at com.xz.springCoudTask.SpringCloudTaskApplication$TestCommandLineRunner.run(SpringCloudTaskApplication.java:31) ~[classes/:na]    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    ... 6 common frames omittedProcess finished with exit code 1

7.以下表会在第一次成功执行后创建。

clipboard.png

在task_execution中也可以看到执行记录,包括错误信息

clipboard.png

解读

spring cloud task生命周期

1.在任务开始之前(即在spring初始化之后执行任何CommandLineRunnerApplicationRunner实现之前)TaskRepository创建一个记录记录开始事件的条目,此事件SmartLifecycle#start由Spring Framework触发,来向系统指出所有bean都可以使用。

The recording of a task will only occur upon the successful bootstrapping of an ApplicationContext. If the context fails to bootstrap at all, the task’s execution will not be recorded.

任务的记录只有当bean可以成功加载时才会被记录,如果失败则不会被记录。

2.在Spring Boot加载完成所有的bean之后,任务执行并更新数据库中的执行结果和状态,最后退出。

转载地址:http://kldul.baihongyu.com/

你可能感兴趣的文章
《Arduino奇妙之旅:智能车趣味制作天龙八步》一3.2 构建小发明
查看>>
《Cisco安全防火墙服务模块(FWSM)解决方案》——第2章防火墙服务模块概述
查看>>
Go语言项目(kingshard)性能优化实例剖析
查看>>
安全预警:ImageMagick 图象处理软件存在远程代码执行(CVE-2016-3714)
查看>>
Google 为什么要把最重要的秘密开源?
查看>>
《Hadoop大数据分析与挖掘实战》——1.5节餐饮服务中的大数据应用
查看>>
《ANSYS Workbench 14有限元分析自学手册》——2.5 体操作
查看>>
《交互式程序设计 第2版》一第1章 交互设计导论
查看>>
ARM拟将ARM核心置入未来的Fusion APU中
查看>>
3分钟参与阿里云《金融行业云上信任报告》调查问卷,98%的几率拿到代金券
查看>>
《C语言编程魔法书:基于C11标准》——2.9 本章小结
查看>>
《移动数据挖掘》—— 1.4 本书简介
查看>>
菲尔兹奖得主维拉尼:七个点子帮你找到科研灵感
查看>>
《C语言程序设计与实践(第2版)》——导读
查看>>
《Java EE 7精粹》—— 第2章 Servlets 2.1 WebServlet
查看>>
《计算机科学概论(第12版)》—第1章1.4节用位模式表示信息
查看>>
C2B前还有S2b,阿里携手产学研探索新零售时代的供应链未来
查看>>
Linux集群和自动化维2.4.2 sed的用法示例
查看>>
为 Kodi 自制遥控器
查看>>
《OpenGL ES 3.x游戏开发(上卷)》一1.2 搭建Android开发环境
查看>>