【Spring Boot】构造、访问Restful Webservice与定时任务
Spring Boot Guides Examples(1~3)
创建一个RESTful Web Service
- 使用Eclipse 创建一个 Spring Boot项目
Project -> Other -> Spring Boot -> Spring Starter Project
- 直接找到,spring boot自动创建的application类,
#我的是 RestfulWebService1Application.java
右键 -> Run As -> Java Application 运行
------------------console result---------------------
#看见下面两行,则开启成功
2019-02-24 10:38:42.935 INFO 6724 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-02-24 10:38:42.940 INFO 6724 --- [ main] c.e.kane.RestfulWebService1Application : Started RestfulWebService1Application in 4.108 seconds (JVM running for 5.631)
- 打开浏览器,键入 localhost:8080会得到下面的报错信息,因为我们还没有定义Controller
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Feb 24 10:39:50 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
## 可以参考下面的网址,对Whitelabel Error Page 自定义
https://www.baeldung.com/spring-boot-custom-error-page
注:可以自定义该页面,到官网查看
- 开始写如一些java类
// 在Application同级目录下创建Model 文件夹,增加Greeting 类
// Greeting.java
package com.example.kane.Model;
public class Greeting{
private final long id;
private final String content;
public Greeting (long id , String content){
this.id = id ;
this.content = content;
}
public long getId(){
return id;
}
public String getContent(){
return content;
}
}
// 在Application同级目录下创建 Controller文件夹,增加GreetingController
// GreetingController.java
package com.example.kane.Controller;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
// RestController是Spring4的新的注解,被注解的controller返回域对象,不是view
// 它是@Controller和@ResponseBody的缩写
import org.springframework.web.bind.annotation.RestController;
import com.example.kane.Model.*;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
- 访问 localhost:8080/greeting
# 页面结果
{"id":1,"content":"Hello, World!"}
- 至此一个简单的Restful Web Service 搭好了
注:官方的关于Restful Web Service 网址 https://spring.io/guides/gs/rest-service/
创建一个计划的任务 Scheduling Tasks
- 创建schdule task类
package com.example.kane;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SchduleTask {
private static final Logger log = LoggerFactory.getLogger(SchduleTask.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
- 更改Application 类,增加@EnableScheduling
package com.example.kane;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class RestfulWebService1Application {
public static void main(String[] args) {
SpringApplication.run(RestfulWebService1Application.class, args);
}
}
- 结果,会在console中看到如下输出
2019-02-24 12:00:14.770 INFO 21096 --- [ scheduling-1] com.example.kane.SchduleTask : The time is now 12:00:14
2019-02-24 12:00:19.770 INFO 21096 --- [ scheduling-1] com.example.kane.SchduleTask : The time is now 12:00:19
2019-02-24 12:00:24.770 INFO 21096 --- [ scheduling-1] com.example.kane.SchduleTask : The time is now 12:00:24
## 不停地运行Schdule函数
- 其他的Schdule选项
https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling
// 等待上一个执行之后5秒执行下一次
@Scheduled(fixedDelay=5000)
//-------------------------------------
//上一次开启之后5秒执行下一次,无论第一次是否执行完成
@Scheduled(fixedRate = 5000)
//-------------------------------------
// 使用cron 进行定时的安排,语法与linux cronjob相同
@Scheduled(cron="*/5 * * * * MON-FRI")
注:cron表达式规则
Seconds Minutes Hours DayofMonth Month DayofWeek Year
或
Seconds Minutes Hours DayofMonth Month DayofWeek
| 字段 | 允许值 | 允许的特殊字符 |
|---|---|---|
| 秒(Seconds) | 0~59的整数 | , - * / 四个字符 |
| 分(Minutes) | 0~59的整数 | , - * / 四个字符 |
| 小时(Hours) | 0~23的整数 | , - * / 四个字符 |
| 日期(DayofMonth) | 1~31的整数(但是你需要考虑你月的天数) | ,- * ? / L W C 八个字符 |
| 月份(Month) | 1~12的整数或者 JAN-DEC | , - * / 四个字符 |
| 星期(DayofWeek) | 1~7的整数或者 SUN-SAT (1=SUN) | , - * ? / L C # 八个字符 |
| 年(可选,留空)(Year) | 1970~2099 | , - * / 四个字符 |
消费一个Restful Web Service
这里的消费意为在java中访问一些Restful API 并获得想要的内容。
- 更改 Application.java文件
package com.example.kane;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class RestfulWebService1Application {
private static final Logger log = LoggerFactory.getLogger(RestfulWebService1Application.class);
public static void main(String[] args) {
// 不启动Spring boot的application,直接运行RestTemplate
// SpringApplication.run(RestfulWebService1Application.class, args);
RestTemplate restTemplate = new RestTemplate();
System.out.println(Quote.class);
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
}
/* 下面的代码官方说明是要管理RestTemplate,不明白什么意思
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}*/
}
- 定义一个Quote.java类
// Quote 定义的时候需要知道 restful api 返回的json对象都有什么属性,如果Quote中定义的属性在api中不存在那么将被复制为null,
//我将官网的type属性更改为 type1属性后,结构显示type1:null
package com.example.kane;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type1;
private Value value;
public Quote() {
}
public String getType() {
return type1;
}
public void setType(String type) {
this.type1 = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type1 + '\'' +
", value=" + value +
'}';
}
}
- 定义Value.java
//value 与 quote相同,定义了这两个类 主要是http://gturnquist-quoters.cfapps.io/api/random返回的json对象中有这两个类
package com.example.kane;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
- 上结果
20:59:39.613 [main] INFO com.example.kane.RestfulWebService1Application - Quote{type='null', value=Value{id=4, quote='Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration.'}}
【Spring Boot】构造、访问Restful Webservice与定时任务的更多相关文章
- Spring Boot实战:Restful API的构建
上一篇文章讲解了通过Spring boot与JdbcTemplate.JPA和MyBatis的集成,实现对数据库的访问.今天主要给大家分享一下如何通过Spring boot向前端返回数据. 在现在的开 ...
- Spring Boot Hello World (restful接口)例子
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版
一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...
- SpringBoot实战(十)之使用Spring Boot Actuator构建RESTful Web服务
一.导入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http ...
- spring boot 配置访问其他模块包中的mapper和xml
maven项目结构如下,这里只是简单测试demo,使用的springboot版本为2.1.3.RELEASE 1.comm模块主要是一些mybatis的mapper接口和对应的xml文件,以及数据库表 ...
- Spring Boot 2.X(十二):定时任务
简介 定时任务是后端开发中常见的需求,主要应用场景有定期数据报表.定时消息通知.异步的后台业务逻辑处理.日志分析处理.垃圾数据清理.定时更新缓存等等. Spring Boot 集成了一整套的定时任务工 ...
- 06.深入浅出 Spring Boot - 数据访问之Druid
代码下载:https://github.com/Jackson0714/study-spring-boot.git 一.Druid是什么? 1.Druid是数据库连接池,功能.性能.扩展性方面都算不错 ...
- 07.深入浅出 Spring Boot - 数据访问之Mybatis(附代码下载)
MyBatis 在Spring Boot应用非常广,非常强大的一个半自动的ORM框架. 代码下载:https://github.com/Jackson0714/study-spring-boot.gi ...
- Spring Boot数据访问之动态数据源切换之使用注解式AOP优化
在Spring Boot数据访问之多数据源配置及数据源动态切换 - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中详述了如何配置多数据源及多数据源之间的动态切换.但是需要读数据库的地方,就 ...
随机推荐
- Windows7上完全卸载Oracle 12c操作步骤
注:本文来源于:< Windows7上完全卸载Oracle 12c操作步骤 > 1.关闭Oracle所有的服务,按[win+R]运行[services.msc]找到所有Oracle开头的 ...
- Confluence 6 使用 Jira 管理用户
如果你已经使用了 Jira 来管理你的任务和 issue 的话,你可以选择将 Jira 和 Confluence 整合在一起,将用户管理集中到一个地方.你可以控制你 Jira 中的用户组是否具有使用 ...
- Confluence 6 关于统一插件管理器
所有的组件通过 统一插件管理器(Universal Plugin Manager)进行管理,这个也被称为 UPM.UPM 可以在几乎所有的 Atlassian 应用中找到,能够提供完整同意的插件安装管 ...
- Ionic3.0 输入状态时隐藏Tabs栏
刚接触ionic3 不久 ,发现遍地都是坑,昨天遇到一个问题就是当键盘弹起的时候tabs 也被 弹了起来,最初预想是放在tabs 的一个子页面内处理这个问题, Tabs隐藏后,我们发现底部有部分空白, ...
- 【kafka】设置指定topic和group_id消耗的offset
该博文方法有问题,正确方案在http://www.cnblogs.com/dplearning/p/7992994.html 背景: 搭建了一个kafka集群,建立了topic test,用group ...
- 使用Calendar获取上一月,下一月,上一年,下一年的当天日期
Calendar的add(int field,int amount)方法 field 表示月或年,天等字段 amount 代表增量或减量 例如: 上月的当天日期 Calendar cal = Cal ...
- jmeter BeanShell实例-----两个变量之间的断言对比
jmeter BeanShell实例-----两个变量之间的断言对比 在jmeter的中,断言没法对两个变量的进行对比后判断,只能使用Bean Shell断言来进行,总是有人来问怎么写呢.这里写一个简 ...
- C++ Primer 笔记——迭代器
iostream迭代器 1.虽然iostream类不是容器,但是标准库定义了可以用于IO的迭代器.创建一个流迭代器的时候必须指定要读写的类型.我们可以对任何具有输入运算符(>>)的类型定义 ...
- js instanceof 检测某个对象是否是另一个对象的实例
例如File对象 $("#file").change(function(){ console.log($(this)[0].files[0]) console.log($(this ...
- new/new[]和delete/delete[]是如何分配空间以及释放空间的
C++中程序存储空间除栈空间和静态区外,每个程序还拥有一个内存池,这部分内存被称为或堆(heap).程序可以用堆来存储动态分配的对象,即那些在程序运行时创建的对象.动态对象的生存期由程序来控制 ,当动 ...