优秀的编程知识分享平台

网站首页 > 技术文章 正文

Springboot做一个定时任务(客户端和服务端)

nanyue 2024-08-03 18:11:44 技术文章 8 ℃

目标效果图:

实现步骤

1、选择Create NewProject 创建一个新工程

2、创建一个工程,工程下面可以分模块子模块构建依赖maven构建的生态

3、这里可以添加许多依赖模块包,提供为开发者更大的简便,不用的自己配置复杂的配置文件,用着就是爽

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ernestfei</groupId>
	<artifactId>spring-ernestfei-timertask</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>spring-ernestfei-timertask</name>
	<description>Demo project for Spring Boot</description>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient-cache -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>4.5.3</version>
		</dependency>
		<!--httpclinet请求所需包 https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5.3</version>
		</dependency>
		<!--springboot web启动包-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--springboot读取配置文件类-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson json工具类 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.41</version>
		</dependency>
		<!--操作文件工具类-->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- 可命令行独立编译maven项目下的class文件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<proc>none</proc>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

4、工程创建成功后将配置pom.xml文件,具体配置如上。

5、 工程目录结构如下

6、下面我们配置一下定时任务

启动类中使用 @EnableScheduling 注解来开启任务调度

@SpringBootApplication
@EnableScheduling
public class SpringErnestfeiTimertaskApplication {
 public static void main(String[] args) {
 SpringApplication.run(SpringErnestfeiTimertaskApplication.class, args);
 System.out.println("=======================Springboot实现定时任务客户端demo=========================");
 }
}

7、调度方法如下

@Component
public class TimerTasks {
 private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 @Resource
 private UrlConfig config;
 /**
 * 定时任务上传文件到服务器
 * */
 @Scheduled(cron = "0 0/1 * * * ?")
 public void reportCurrentTime() {
 Date date = new Date();
 File uploadFile = new File(config.getGetFileDir()+"\\1.txt");
 FileUploadClient.uploadPassFile(config.getServerUrl(),uploadFile);
 System.out.println("{客户端定时任务开启每一分钟发送一次}===>>>"+dateFormat.format(date));
 }
}

8、使用HttpClinet实现客户端调度,具体如下

/** * 上传文件 * serverUrl 上传服务器地址 * file 上传的文件 * */ public static void uploadFile(String serverUrl,File file0) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody file = new FileBody(file0); StringBody token = new StringBody("1234567", ContentType.create("text/plain", Consts.UTF_8)); StringBody content = new StringBody(">>>{来自于客户端传来的文件}<<<", ContentType.create("text/plain", Consts.UTF_8)); MultipartEntityBuilder builder =MultipartEntityBuilder.create(); HttpEntity reqEntity = builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("file", file) .addPart("token", token) .addPart("content",content) .setCharset(CharsetUtils.get("UTF-8")).build(); httppost.setEntity(reqEntity); long startTime=System.currentTimeMillis(); System.out.println("====开始执行====" + startTime); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity resEntity = response.getEntity(); if(resEntity!=null){ System.out.println("==resEntity=="+resEntity.getContent()); System.out.println("====中文乱码检测===="); System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8"))); } EntityUtils.consume(resEntity); long endTime=System.currentTimeMillis(); System.out.println("====结束执行====" + endTime); System.out.println("====执行时间====" + (endTime - startTime)); } finally { response.close(); } } catch (ClientProtocolException e) { System.out.println("====服务器端无法连接异常===="); e.printStackTrace(); } catch (IOException e) { System.out.println("====服务器端无法连接异常===="); e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } 9、服务端Contoller层处理客户端调用处理

@RestController
public class FileUploadController {
 @Resource
 private UrlConfig config;
 @PostMapping("uploadFile")
 public Object uploadFile(@RequestParam(value = "file")MultipartFile file,@RequestParam(value = "token")String token,@RequestParam(value = "content",required = false)String content){
 Map<String,Object> resMap = new HashMap<>(8);
 System.out.println("{服务端接受内容}===>>>"+content);
 if(token.equals(config.getToken())){
 System.out.println("{上传的文件名为}===>>>"+file.getOriginalFilename());
 resMap.put("status",200);
 resMap.put("message","服务端返回=上传成功,返回文件"+file.getOriginalFilename());
 }else{
 resMap.put("status",400);
 resMap.put("message","服务端返回=上传失败,TOKEN校验失败!");
 }
 return JSON.toJSONString(resMap);
 }
}

10、读取配置文件中的参数可以使用@ConfigurationProperties 和 @PropertySource 读取配置文件,将参数加载成实例属性。

@Component
@ConfigurationProperties(prefix = UrlConfig.PREFIX)
@PropertySource("classpath:baseConfig.properties")
public class UrlConfig {
 public static final String PREFIX = "config";
 private String serverUrl;
 private String getFileDir;
 private String token;
 public void setToken(String token) {
 this.token = token;
 }
 public String getToken() {
 return token;
 }
 public void setServerUrl(String serverUrl) {
 this.serverUrl = serverUrl;
 }
 public String getServerUrl() {
 return serverUrl;
 }
 public void setGetFileDir(String getFileDir) {
 this.getFileDir = getFileDir;
 }
 public String getGetFileDir() {
 return getFileDir;
 }

自此一个简单的demo就轻松实现了客户端向服务端定时发送文件的定时任务功能。不得不感慨SpringBoot的强大之处。

最近发表
标签列表