SpringBoot使用记录-20170623更新

来源:互联网 发布:师洋的淘宝店名字 编辑:程序博客网 时间:2024/06/05 06:38

一、 CommandLineRunner与PostConstruct

从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@PostConstruct和@PreConstruct。

被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。

被@PreConstruct修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。

之前运行@PostConstruct出现问题,发现在@PostConstruct修饰的方法结束之前,web应用无法正常执行,无法处理web请求。

Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。不过实现CommandLineRunner不会影响其他web请求。


二、@Scheduled

在SpringBoot中使用@Scheduled需要使用@EnableScheduling注解,修改服务器时间后到规定时间不执行【Scheduled中有一个任务按照间隔时间来执行Scheduled】,后续观察是否可以修正到正常的时间。Scheduled只记录相对时间来执行调度中间并不会校对时间,所以修改系统的小伙伴需要重启应用。


三、RestTemplate

在Spring中调用接口可以使用restTemplate比较方便,调用上传、下载的接口写法比较麻烦,我在这里记录一下上传文件的代码

根据上传接口需要的参数传递参数:返回结果用com.alibaba.fastjson.JSONObject做格式转换。

下载因为是数据流所以应该是byte[]数组  (此处百度测试)

FileSystemResource resource = new FileSystemResource(new File(zipPath));  MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();  param.add("file", resource);  param.add("fileClass", InterfaceConstant.FILE_CLASS); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String,Object>>(param);String url = "http://" + InterfaceConstant.FILE_SERVER_NAME + "/" + InterfaceConstant.FILE_UPLOAD_FUN;ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Response.class);Response body = response.getBody();System.out.println("上传文件返回结果:" + body);Attachment attachment = response.getBody().getObjectBody(Attachment.class);

四、@Async

async 异步,通过注解开启线程实现异步

1、不能在静态方法上使用

2、在外层的事物注解不生效

修饰在方法上,如果需要返回结果,返回类型为future,通过future.isDone 方法判断结果返回与否。

(猜测)有返回结果的情况应该是开启线程池执行了实现了Callable接口的线程,其他情况开启普通线程。

应用场景:多个操作可以并发执行,缩短需要等待的时间。




0 0