如何配置允许跨域访问
现在开发的项目一般都是前后端分离的项目,所以跨域访问会经常使用。
1、单个控制器方法CORS注解
@RestController
@RequestMapping("/system/test")
public class TestController {
@CrossOrigin
@GetMapping("/{id}")
public AjaxResult getUser(@PathVariable Integer userId) {
// ...
}
@DeleteMapping("/{userId}")
public AjaxResult delete(@PathVariable Integer userId) {
// ...
}
}
2、整个控制器添加CORS注解
@CrossOrigin(origins = "http://localhost:8088/", maxAge = 3600)
@RestController
@RequestMapping("/system/test")
public class TestController {
@GetMapping("/{id}")
public AjaxResult getUser(@PathVariable Integer userId) {
// ...
}
@DeleteMapping("/{userId}")
public AjaxResult delete(@PathVariable Integer userId) {
// ...
}
}
3、全局CORS配置,编写MvcConfig.java
/**
* @author yuxt
* @date 2021/4/22
*/
@Configuration
public class MvcConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
/**
* web跨域访问配置
*/
@Override
public void addCorsMappings(CorsRegistry registry)
{
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 是否允许证书
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("GET", "POST", "DELETE", "PUT")
// 设置允许的header属性
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
};
}
}
如何优雅地关闭后台系统
一般关闭Java程序的方式:
ps -ef|grep java #获取进程pid
kill -9 pid #杀死进程
存在问题:正在执行的业务操作会被迫停止,可能出现错误的业务数据。
优雅地关闭后台系统,就是指对应用进程发送停止指令之后,能够保证正在执行的业务操作不受影响,可以继续完成已有请求的处理后关闭,同时停止处理新来的请求。
在 Spring Boot 2.3及以后版本中增加了新特性:优雅停止,目前 Spring Boot 内置的四个嵌入式 Web 服务器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反应式和基于Servlet的Web应用程序都支持优雅停止。
1,添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
2,配置application.yml
management:
endpoint:
shutdown:
enabled: true
endpoints:
web:
exposure:
include: shutdown
3、启动程序,访问http://localhost:8080/actuator,得到停止系统的请求路径
4、打开控制台或者使用postman,先发送一个耗时较长的请求,再发送 curl -X POST http://localhost:8080/actuator/shutdown,可以发现在之前的请求返回结果后再返回
{"message": "Shutting down, bye..."}
系统关闭!