程序员@老李 - Java 2024-08-29T10:01:00+08:00 Typecho https://blog.mostion.com/feed/atom/category/java/ <![CDATA[SpringBoot 整合线程池]]> https://blog.mostion.com/archives/53/ 2024-08-29T10:01:00+08:00 2024-08-29T10:01:00+08:00 Jason http://blog.mostion.com 步骤如下:

1. 启动类加入 @EnableAsync 注解

@SpringBootApplication
@EnableAsync
public class FacadeH5Application {
    public static void main(String[] args) {
        SpringApplication.run(FacadeH5Application.class, args);
    }
}

2. 在方法上加 @Async 注解

@Async
public void m1() {
    //do something
}

3. 创建线程池配置文件

# 核心线程数
spring.task.execution.pool.core-size=8  
# 最大线程数
spring.task.execution.pool.max-size=16
# 空闲线程存活时间
spring.task.execution.pool.keep-alive=60s
# 是否允许核心线程超时
spring.task.execution.pool.allow-core-thread-timeout=true
# 线程队列数量
spring.task.execution.pool.queue-capacity=100
# 线程关闭等待
spring.task.execution.shutdown.await-termination=false
spring.task.execution.shutdown.await-termination-period=
# 线程名称前缀
spring.task.execution.thread-name-prefix=task-
@Configuration
public class ThreadPoolConfig {
    @Bean
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //设置最大线程数
        executor.setMaxPoolSize(20);
        //设置队列容量
        executor.setQueueCapacity(20);
        //设置线程活跃时间
        executor.setKeepAliveSeconds(30);
        //设置线程名称前缀
        executor.setThreadNamePrefix("sendSms-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中任务的等待时间
        executor.setAwaitTerminationSeconds(60);

        return executor;
    }
}

配置多个线程池

@Configuration
public class ThreadPoolConfig {
    @Bean("ThreadPool1")
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ......
        return executor;
    }
    @Bean("ThreadPool2")
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ......
        return executor;
    }
}

在使用 @Async 注解时就需要指定具体的线程池

@Async("ThreadPool1")
public void m1() {
    //do something
}
]]>
<![CDATA[SpringBoot静态方法调用Spring容器bean的几种方案]]> https://blog.mostion.com/archives/49/ 2023-12-14T13:47:13+08:00 2023-12-14T13:47:13+08:00 Jason http://blog.mostion.com 今天遇到一个问题,需要在静态方法中调用哦那个容器Bean,大致代码如下:

@Autowired
private static RedisUtil redisUtilBean;

public static String getMsgByRedis(){
    redisUtilBean.get("xxx")  //这里redisUtilBean一定会是NULL值
}

为什么会出现这种情况?原因是Spring容器的依赖注入是依赖set方法,而set方法是实例对象的方法,注入依赖时是无法注入静态成员变量的,在调用的时候依赖的Bean才会为null;

解决方案一

使用@PostConstruct注解:

@Autowired
private RedisUtil redisUtilBean;
    
//由于静态方法无法使用注入的Bean 定义静态变量
private static RedisUtil redisUtil;

//当容器实例化当前受管Bean时@PostConstruct注解的方法会被自动触发,借此来实现静态变量初始化
@PostConstruct
public void init(){
   this.redisUtil = redisUtilBean;
}
    
public static String getMsgByRedis(){
   redisUtil.get("xxx")  //这里可以正常使用
}

解决方案二

利用springboot的启动类中,SpringApplication.run() 方法返回的是一个ConfigurableApplicationContext对象通过定义static变量ConfigurableApplicationContext,利用容器的getBean方法获得依赖对象;

@SpringBootApplication
@EnableTransactionManagement
public class Application {
    //定义静态的ApplicationContext
    public static ConfigurableApplicationContext applicationContext;
    public static void main(String[] args) {
        applicationContext = SpringApplication.run(Application.class, args);
    }
}

//调用  注意Application是我们SpringBoot的启动类
public static String getMsgByRedis(){
    Application.applicationContext.getBean(RedisUtil .class).get("xxx") 
}

解决方案三

在我们以前SpringMVC中常用的工具类,通过实现ApplicationContextAware接口,网上也很多这里就把工具类贴出来即可;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.toher.common.utils.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 *
 * @author 李怀明
 * @version 2017-01-02
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    //实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    //取得存储在静态变量中的ApplicationContext.
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    //从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    //从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
    //如果有多个Bean符合Class, 取出第一个.
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        @SuppressWarnings("rawtypes")
        Map beanMaps = applicationContext.getBeansOfType(clazz);
        if (beanMaps != null && !beanMaps.isEmpty()) {
            return (T) beanMaps.values().iterator().next();
        } else {
            return null;
        }
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }

    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

}

调用方法:

RedisUtil redisUtil= (RedisUtil) SpringContextHolder.getBean(RedisUtil.class);

结束,感谢!

]]>
<![CDATA[SpringBoot 自定义线程池]]> https://blog.mostion.com/archives/48/ 2023-11-29T08:51:00+08:00 2023-11-29T08:51:00+08:00 Jason http://blog.mostion.com 我们都知道spring只是为我们简单的处理线程池,每次用到线程总会new 一个新的线程,效率不高,所以我们需要自定义一个线程池。

本教程目录:

  1. 自定义线程池
  2. 配置spring默认的线程池

1. 自定义线程池

1.1 修改application.properties

task.pool.corePoolSize=20
task.pool.maxPoolSize=40
task.pool.keepAliveSeconds=300
task.pool.queueCapacity=50

1.2 线程池配置属性类TaskThreadPoolConfig.java

import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * 线程池配置属性类
 * Created by Fant.J.
 */
@ConfigurationProperties(prefix = "task.pool")
public class TaskThreadPoolConfig {
    private int corePoolSize;

    private int maxPoolSize;

    private int keepAliveSeconds;

    private int queueCapacity;
    ...getter and setter methods...
}

1.3 创建线程池 TaskExecutePool.java

/**
 * 创建线程池
 * Created by Fant.J.
 */
@Configuration
@EnableAsync
public class TaskExecutePool {
    @Autowired
    private TaskThreadPoolConfig config;

    @Bean
    public Executor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(config.getCorePoolSize());
        //最大线程数
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //队列容量
        executor.setQueueCapacity(config.getQueueCapacity());
        //活跃时间
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        //线程名字前缀
        executor.setThreadNamePrefix("MyExecutor-");

        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

1.4 创建线程任务

/**
* Created by Fant.J.
*/
@Component
public class AsyncTask {
   protected final Logger logger = LoggerFactory.getLogger(this.getClass());

   @Async("myTaskAsyncPool")  //myTaskAsynPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池
   public void doTask1(int i) throws InterruptedException{
       logger.info("Task"+i+" started.");
   }
}

1.5 修改启动类

给启动类添加注解
@EnableAsync
@EnableConfigurationProperties({TaskThreadPoolConfig.class} ) // 开启配置属性支持

1.6 测试

protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AsyncTask asyncTask;

    @Test
    public void AsyncTaskTest() throws InterruptedException, ExecutionException {

        for (int i = 0; i < 100; i++) {
            asyncTask.doTask1(i);
        }
        logger.info("All tasks finished.");
    }

2. 配置默认的线程池

我本人喜欢用这种方式的线程池,因为上面的那个线程池使用时候总要加注解@Async("myTaskAsyncPool"),而这种重写spring默认线程池的方式使用的时候,只需要加@Async注解就可以,不用去声明线程池类。

2.1 获取属性配置类

这个和上面的TaskThreadPoolConfig类相同,这里不重复

2.2 NativeAsyncTaskExecutePool.java 装配线程池

/**
 * 原生(Spring)异步任务线程池装配类
 * Created by Fant.J.
 */
@Slf4j
@Configuration
public class NativeAsyncTaskExecutePool implements AsyncConfigurer{


    //注入配置类
    @Autowired
    TaskThreadPoolConfig config;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(config.getCorePoolSize());
        //最大线程数
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //队列容量
        executor.setQueueCapacity(config.getQueueCapacity());
        //活跃时间
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        //线程名字前缀
        executor.setThreadNamePrefix("MyExecutor-");

        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }


    /**
     *  异步任务中异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {

            @Override
            public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
                log.error("=========================="+arg0.getMessage()+"=======================", arg0);
                log.error("exception method:"+arg1.getName());
            }
        };
    }
}

2.3 线程任务类AsyncTask .java

@Component
public class AsyncTask {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Async
    public void doTask2(int i) throws InterruptedException{
        logger.info("Task2-Native"+i+" started.");
    }
}

2.4 测试

@Test
public void AsyncTaskNativeTest() throws InterruptedException, ExecutionException {
    for (int i = 0; i < 100; i++) {
        asyncTask.doTask2(i);
    }
    logger.info("All tasks finished.");
}

2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-8] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native6 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-3] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native1 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native7 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native21 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native22 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native23 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native24 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native25 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native26 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native27 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native28 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native29 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native30 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native31 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native32 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native33 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native34 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native35 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native36 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native37 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native38 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native39 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native40 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native41 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native42 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native43 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native44 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native45 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native46 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native47 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-7] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native5 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-7] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native49 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-7] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native50 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-11] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native9 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native4 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native53 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native54 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native55 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native56 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native57 started.
2018-03-25 21:23:07.659 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native58 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native59 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native60 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native61 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native62 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native63 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native64 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native65 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native66 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native67 started.
2018-03-25 21:23:07.660 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native68 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-5] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native3 started.
2018-03-25 21:23:07.655 INFO 4668 --- [ MyExecutor-4] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native2 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-8] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native19 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-2] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native0 started.
2018-03-25 21:23:07.656 INFO 4668 --- [ MyExecutor-3] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native20 started.
2018-03-25 21:23:07.657 INFO 4668 --- [ MyExecutor-10] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native8 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native48 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-7] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native51 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-11] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native52 started.
2018-03-25 21:23:07.658 INFO 4668 --- [ MyExecutor-12] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native10 started.
2018-03-25 21:23:07.661 INFO 4668 --- [ MyExecutor-13] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native11 started.
2018-03-25 21:23:07.662 INFO 4668 --- [ MyExecutor-14] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native12 started.
2018-03-25 21:23:07.662 INFO 4668 --- [ MyExecutor-15] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native13 started.
2018-03-25 21:23:07.663 INFO 4668 --- [ MyExecutor-16] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native14 started.
2018-03-25 21:23:07.663 INFO 4668 --- [ MyExecutor-17] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native15 started.
2018-03-25 21:23:07.663 INFO 4668 --- [ MyExecutor-18] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native16 started.
2018-03-25 21:23:07.663 INFO 4668 --- [ MyExecutor-19] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native17 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-20] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native18 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-21] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native69 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ main] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native89 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-6] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native90 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-22] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native70 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-5] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native91 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-5] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native92 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-8] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native93 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-2] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native94 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-10] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native95 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-3] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native96 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-7] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native98 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-9] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native97 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ MyExecutor-11] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native99 started.
2018-03-25 21:23:07.664 INFO 4668 --- [ main] com.laojiao.securitydemo.ControllerTest : All tasks finished.
2018-03-25 21:23:07.666 INFO 4668 --- [ MyExecutor-23] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native71 started.
2018-03-25 21:23:07.667 INFO 4668 --- [ MyExecutor-24] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native72 started.
2018-03-25 21:23:07.667 INFO 4668 --- [ MyExecutor-25] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native73 started.
2018-03-25 21:23:07.669 INFO 4668 --- [ MyExecutor-26] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native74 started.
2018-03-25 21:23:07.669 INFO 4668 --- [ MyExecutor-27] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native75 started.
2018-03-25 21:23:07.673 INFO 4668 --- [ MyExecutor-28] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native76 started.
2018-03-25 21:23:07.674 INFO 4668 --- [ MyExecutor-29] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native77 started.
2018-03-25 21:23:07.674 INFO 4668 --- [ MyExecutor-30] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native78 started.
2018-03-25 21:23:07.676 INFO 4668 --- [ MyExecutor-31] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native79 started.
2018-03-25 21:23:07.677 INFO 4668 --- [ MyExecutor-32] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native80 started.
2018-03-25 21:23:07.677 INFO 4668 --- [ MyExecutor-33] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native81 started.
2018-03-25 21:23:07.677 INFO 4668 --- [ MyExecutor-34] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native82 started.
2018-03-25 21:23:07.678 INFO 4668 --- [ MyExecutor-35] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native83 started.
2018-03-25 21:23:07.679 INFO 4668 --- [ MyExecutor-36] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native84 started.
2018-03-25 21:23:07.679 INFO 4668 --- [ MyExecutor-37] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native85 started.
2018-03-25 21:23:07.679 INFO 4668 --- [ MyExecutor-38] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native86 started.
2018-03-25 21:23:07.680 INFO 4668 --- [ MyExecutor-39] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native87 started.
2018-03-25 21:23:07.680 INFO 4668 --- [ MyExecutor-40] c.l.securitydemo.mythreadpool.AsyncTask : Task2-Native88 started.

作者:PlayInJava
链接:https://juejin.cn/post/6844903584857849870
]]>
<![CDATA[Spring Boot中如何优雅地实现异步调用]]> https://blog.mostion.com/archives/30/ 2023-11-03T18:25:00+08:00 2023-11-03T18:25:00+08:00 Jason http://blog.mostion.com 前言

SpringBoot想必大家都用过,但是大家平时使用发布的接口大都是同步的,那么你知道如何优雅的实现异步呢?
这篇文章就是关于如何在Spring Boot中实现异步行为的。但首先,让我们看看同步和异步之间的区别。

  • 同步编程:在同步编程中,任务一次执行一个,只有当一个任务完成时,下一个任务才会被解除阻塞。
  • 异步编程:在异步编程中,可以同时执行多个任务。您可以在上一个任务完成之前转到另一个任务。

WX20231103-181655@2x.png

Spring Boot中,我们可以使用@Async注解来实现异步行为。

实现步骤

  1. 定义一个异步服务接口 AsyncService.java
public interface AsyncService {
    void asyncMethod() throws InterruptedException;
    Future<String> futureMethod() throws InterruptedException;
}
  1. 实现定义的接口 AsyncServiceImpl.java
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService  {

    @Async
    @Override
    public void asyncMethod() throws InterruptedException {
        Thread.sleep(3000);
        log.info("Thread: [{}], Calling other service..", Thread.currentThread().getName());
    }

    @Async
    @Override
    public Future<String> futureMethod() throws InterruptedException {
        Thread.sleep(5000);
        log.info("Thread: [{}], Calling other service..", Thread.currentThread().getName());
        return new AsyncResult<>("task Done");
    }
}
  • AsyncServiceImpl 是一个 spring 管理的 bean
  • 您的异步方法必须是公共的,而且是被 @Async 注解修饰。
  • 返回类型被限制为 voidFuture
  1. 定义一个控制器AsyncController.java
@EnableAsync
@RestController
@Slf4j
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/async")
    public String asyncCallerMethod() throws InterruptedException {
        long start = System.currentTimeMillis();
        log.info("call async method, thread name: [{}]", Thread.currentThread().getName());
        asyncService.asyncMethod();
        String response = "task completes in :" +
                (System.currentTimeMillis() - start) + "milliseconds";
        return response;
    }

    @GetMapping("/asyncFuture")
    public String asyncFuture() throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        log.info("call async method, thread name: [{}]", Thread.currentThread().getName());
        Future<String> future = asyncService.futureMethod();
        // 阻塞获取结果
        String taskResult = future.get();
        String response = taskResult + "task completes in :" +
                (System.currentTimeMillis() - start) + "milliseconds";
        return response;
    }
}
  • 关键点,需要添加启用异步的注解@EnableAsync ,当然这个注解加在其他地方也ok得。
  • 当外部调用该接口时,asyncMethod() 将由默认任务执行程序创建的另一个线程执行,主线程不需要等待完成异步方法执行。
  1. 运行一下

现在我们运行一下看看,是不是异步返回的。

WX20231103-182039@2x.png

  • 可以看到调用 /async 接口,最终一步调用了方法。

WX20231103-182050@2x.png

  • 调用 /asyncFuture ,发现返回5秒多,难道不是异步的吗?其实也是异步的,看日志可以看出来,只不过我们返回的是 Future ,调用 Futrue.get() 是阻塞的。

自定义异步任务执行器和异常处理

我们现在看看如果异常方法中报错了会怎么样?修改异步代码如下所示,会抛运行时异常:

WX20231103-182249@2x.png

再次执行异步接口,如下所示,会使用默认的线程池和异常处理。

WX20231103-182320@2x.png

我们也可以自定义异步方法的处理异常和异步任务执行器,我们需要配置 AsyncUncaughtExceptionHandler,如下代码所示:

@Configuration
public class AsynConfiguration extends AsyncConfigurerSupport {
   @Override
   public Executor getAsyncExecutor() {
      ThreadPoolTaskExecutor executor = new 
                ThreadPoolTaskExecutor();
      executor.setCorePoolSize(3);
      executor.setMaxPoolSize(4);
      executor.setThreadNamePrefix("asyn-task-thread-");
      executor.setWaitForTasksToCompleteOnShutdown(true);
      executor.initialize();
      return executor;
  }
  @Override
  public AsyncUncaughtExceptionHandler  
         getAsyncUncaughtExceptionHandler() {
     return new AsyncUncaughtExceptionHandler() {
   
        @Override
        public void handleUncaughtException(Throwable ex, 
           Method method, Object... params) {
           System.out.println("Exception: " + ex.getMessage());
           System.out.println("Method Name: " + method.getName());
           ex.printStackTrace();
        }
    };
  }
}

再次运行,得到的结果如下:

WX20231103-182416@2x.png

@Async如何工作的

必须通过使用 @EnableAsync 注解注解主应用程序类或任何直接或间接异步方法调用程序类来启用异步支持。主要通过代理模式实现,默认模式是 Proxy,另一种是 AspectJ。代理模式只允许通过代理拦截调用。永远不要从定义它的同一个类调用异步方法,它不会起作用。
当使用 @Async 对方法进行注解时,它会根据“proxyTargetClass”属性为该对象创建一个代理。当 spring 执行这个方法时,默认情况下它会搜索关联的线程池定义。上下文中唯一的 spring 框架 TaskExecutor bean 或名为“taskExecutor”的 Executor bean。如果这两者都不可解析,默认会使用spring框架 SimpleAsyncTaskExecutor 来处理异步方法的执行。

总结

在本文中,我们演示了在 spring boot 中如何使用 @Async 注解和异步方法中的异常处理实现异步行为。我们可以在一个接口中,需要访问不同的资源,比如异步调用各个其他服务的接口,可以使用 @Async,然后将结果通过 Future 的方式阻塞汇总,不失为一个提高性能的好方法。

]]>
<![CDATA[SpringBoot外部配置文件的用法]]> https://blog.mostion.com/archives/19/ 2023-11-03T14:19:00+08:00 2023-11-03T14:19:00+08:00 Jason http://blog.mostion.com 1. 加载外部配置文件
spring.config.additional-location=file:/etc/myapp/config/,classpath:/config/
-Dspring.config.additional-location=file:/etc/myapp/config/,classpath:/config/

2. 配置文件在 jar 包的同级目录下的 config 目录下,优先级最高

3. 读取外部 logback 配置文件

java -jar -Dlogging.config=./config/logback-spring.xml datasync-web.jar
]]>
<![CDATA[SpringBoot项目中使用缓存Cache的正确姿势]]> https://blog.mostion.com/archives/13/ 2023-11-03T13:52:16+08:00 2023-11-03T13:52:16+08:00 Jason http://blog.mostion.com 前言

缓存可以通过将经常访问的数据存储在内存中,减少底层数据源如数据库的压力,从而有效提高系统的性能和稳定性。我想大家的项目中或多或少都有使用过,我们项目也不例外,但是最近在review公司的代码的时候写的很蠢且low, 大致写法如下:

public User getById(String id) {
    User user = cache.getUser();
    if(user != null) {
        return user;
    }
    // 从数据库获取
    user = loadFromDB(id);
    cahce.put(id, user);
    return user;
}

其实Spring Boot 提供了强大的缓存抽象,可以轻松地向您的应用程序添加缓存。本文就讲讲如何使用 Spring 提供的不同缓存注解实现缓存的最佳实践。

启用缓存@EnableCaching

现在大部分项目都是是SpringBoot项目,我们可以在启动类添加注解@EnableCaching来开启缓存功能。

@SpringBootApplication
@EnableCaching
public class SpringCacheApp {

    public static void main(String[] args) {
        SpringApplication.run(Cache.class, args);
    }
}

既然要能使用缓存,就需要有一个缓存管理器Bean,默认情况下,@EnableCaching 将注册一个ConcurrentMapCacheManagerBean,不需要单独的 bean 声明。ConcurrentMapCacheManager将值存储在ConcurrentHashMap的实例中,这是缓存机制的最简单的线程安全实现。

自定义缓存管理器

默认的缓存管理器并不能满足需求,因为她是存储在jvm内存中的,那么如何存储到redis中呢?这时候需要添加自定义的缓存管理器。

1.添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 配置 Redis 缓存

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public CacheManager cacheManager() {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .disableCachingNullValues()
            .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory())
            .cacheDefaults(redisCacheConfiguration)
            .build();

        return redisCacheManager;
    }
}

现在有了缓存管理器以后,我们如何在业务层面操作缓存呢?

我们可以使用@Cacheable@CachePut@CacheEvict 注解来操作缓存了。

@Cacheable

该注解可以将方法运行的结果进行缓存,在缓存时效内再次调用该方法时不会调用方法本身,而是直接从缓存获取结果并返回给调用方。

WX20231103-131849@2x.png

例子1:缓存数据库查询的结果。

@Service
public class MyService {

    @Autowired
    private MyRepository repository;

    @Cacheable(value = "myCache", key = "#id")
    public MyEntity getEntityById(Long id) {
        return repository.findById(id).orElse(null);
    }
}

在此示例中,@Cacheable 注解用于缓存 getEntityById()方法的结果,该方法根据其 ID 从数据库中检索 MyEntity 对象。

但是如果我们更新数据呢?旧数据仍然在缓存中?

@CachePut

然后 @CachePut 出来了, 与 @Cacheable 注解不同的是使用 @CachePut 注解标注的方法,在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式写入指定的缓存中。@CachePut 注解一般用于更新缓存数据,相当于缓存使用的是写模式中的双写模式。

@Service
public class MyService {

    @Autowired
    private MyRepository repository;

    @CachePut(value = "myCache", key = "#entity.id")
    public void saveEntity(MyEntity entity) {
        repository.save(entity);
    }
}

@CacheEvict

标注了 @CacheEvict 注解的方法在被调用时,会从缓存中移除已存储的数据。@CacheEvict 注解一般用于删除缓存数据,相当于缓存使用的是写模式中的失效模式。

WX20231103-132318@2x.png

@Service
public class MyService {

    @Autowired
    private MyRepository repository;

     @CacheEvict(value = "myCache", key = "#id")
    public void deleteEntityById(Long id) {
        repository.deleteById(id);
    }
}

@Caching

@Caching 注解用于在一个方法或者类上,同时指定多个 Spring Cache 相关的注解。

WX20231103-132504@2x.png

例子1:@Caching 注解中的 evict 属性指定在调用方法 saveEntity 时失效两个缓存。

@Service
public class MyService {

    @Autowired
    private MyRepository repository;

    @Cacheable(value = "myCache", key = "#id")
    public MyEntity getEntityById(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Caching(evict = {
        @CacheEvict(value = "myCache", key = "#entity.id"),
        @CacheEvict(value = "otherCache", key = "#entity.id")
    })
    public void saveEntity(MyEntity entity) {
        repository.save(entity);
    }

}

例子2:调用 getEntityById 方法时,Spring会先检查结果是否已经缓存在 myCache 缓存中。如果是,Spring 将返回缓存的结果而不是执行该方法。如果结果尚未缓存,Spring 将执行该方法并将结果缓存在 myCache 缓存中。方法执行后,Spring 会根据 @CacheEvict 注解从 otherCache 缓存中移除缓存结果。

@Service
public class MyService {

    @Caching(
        cacheable = {
            @Cacheable(value = "myCache", key = "#id")
        },
        evict = {
            @CacheEvict(value = "otherCache", key = "#id")
        }
    )
    public MyEntity getEntityById(Long id) {
        return repository.findById(id).orElse(null);
    }

}

例子3:当调用 saveData 方法时,Spring 会根据 @CacheEvict 注解先从 otherCache 缓存中移除数据。然后,Spring 将执行该方法并将结果保存到数据库或外部 API
方法执行后,Spring 会根据 @CachePut 注解将结果添加到 myCachemyOtherCachemyThirdCache 缓存中。Spring 还将根据 @Cacheable 注解检查结果是否已缓存在 myFourthCachemyFifthCache 缓存中。如果结果尚未缓存,Spring 会将结果缓存在适当的缓存中。如果结果已经被缓存,Spring 将返回缓存的结果,而不是再次执行该方法。

@Service
public class MyService {

    @Caching(
        put = {
            @CachePut(value = "myCache", key = "#result.id"),
            @CachePut(value = "myOtherCache", key = "#result.id"),
            @CachePut(value = "myThirdCache", key = "#result.name")
        },
        evict = {
            @CacheEvict(value = "otherCache", key = "#id")
        },
        cacheable = {
            @Cacheable(value = "myFourthCache", key = "#id"),
            @Cacheable(value = "myFifthCache", key = "#result.id")
        }
    )
    public MyEntity saveData(Long id, String name) {
        // Code to save data to a database or external API
        MyEntity entity = new MyEntity(id, name);
        return entity;
    }

}

@CacheConfig

通过 @CacheConfig 注解,我们可以将一些缓存配置简化到类级别的一个地方,这样我们就不必多次声明相关值:

@CacheConfig(cacheNames={"myCache"})
@Service
public class MyService {

    @Autowired
    private MyRepository repository;

    @Cacheable(key = "#id")
    public MyEntity getEntityById(Long id) {
        return repository.findById(id).orElse(null);
    }

    @CachePut(key = "#entity.id")
    public void saveEntity(MyEntity entity) {
        repository.save(entity);
    }

    @CacheEvict(key = "#id")
    public void deleteEntityById(Long id) {
        repository.deleteById(id);
    }
}

Condition & Unless

  • condition作用:指定缓存的条件(满足什么条件才缓存),可用 SpEL 表达式(如 #id>0,表示当入参 id 大于 0
    时才缓存)
  • unless作用 : 否定缓存,即满足 unless 指定的条件时,方法的结果不进行缓存,使用 unless 时可以在调用的方法获取到结果之后再进行判断(如 #result == null,表示如果结果为 null 时不缓存)
//when id >10, the @CachePut works. 
@CachePut(key = "#entity.id", condition="#entity.id > 10")
public void saveEntity(MyEntity entity) {
    repository.save(entity);
}

//when result != null, the @CachePut works.
@CachePut(key = "#id", condition="#result == null")
public void saveEntity1(MyEntity entity) {
    repository.save(entity);
}

清理全部缓存

通过 allEntriesbeforeInvocation 属性可以来清除全部缓存数据,不过 allEntries 是方法调用后清理,beforeInvocation 是方法调用前清理。

//方法调用完成之后,清理所有缓存
@CacheEvict(value="myCache",allEntries=true)
public void delectAll() {
    repository.deleteAll();
}

//方法调用之前,清除所有缓存
@CacheEvict(value="myCache",beforeInvocation=true)
public void delectAll() {
    repository.deleteAll();
}

SpEL表达式

Spring Cache注解中频繁用到SpEL表达式,那么具体如何使用呢?

SpEL 表达式的语法

WX20231103-135021@2x.png

Spring Cache可用的变量

WX20231103-135032@2x.png

最佳实践

通过 Spring 缓存注解可以快速优雅地在我们项目中实现缓存的操作,但是在双写模式或者失效模式下,可能会出现缓存数据一致性问题(读取到脏数据),Spring Cache 暂时没办法解决。最后我们再总结下 Spring Cache 使用的一些最佳实践。

  • 只缓存经常读取的数据:缓存可以显着提高性能,但只缓存经常访问的数据很重要。很少或从不访问的缓存数据会占用宝贵的内存资源,从而导致性能问题。
  • 根据应用程序的特定需求选择合适的缓存提供程序和策略。SpringBoot 支持多种缓存提供程序,包括 EhcacheHazelcastRedis
  • 使用缓存时请注意潜在的线程安全问题。对缓存的并发访问可能会导致数据不一致或不正确,因此选择线程安全的缓存提供程序并在必要时使用适当的同步机制非常重要。
  • 避免过度缓存。缓存对于提高性能很有用,但过多的缓存实际上会消耗宝贵的内存资源,从而损害性能。在缓存频繁使用的数据和允许垃圾收集不常用的数据之间取得平衡很重要。
  • 使用适当的缓存逐出策略。使用缓存时,重要的是定义适当的缓存逐出策略以确保在必要时从缓存中删除旧的或陈旧的数据。
    使用适当的缓存键设计。缓存键对于每个数据项都应该是唯一的,并且应该考虑可能影响缓存数据的任何相关参数,例如用户 ID、时间或位置。
  • 常规数据(读多写少、即时性与一致性要求不高的数据)完全可以使用 Spring Cache,至于写模式下缓存数据一致性问题的解决,只要缓存数据有设置过期时间就足够了。
  • 特殊数据(读多写多、即时性与一致性要求非常高的数据),不能使用 Spring Cache,建议考虑特殊的设计(例如使用 Cancal 中间件等)。
]]>
<![CDATA[SpringBoot 项目解决跨域的几种方案]]> https://blog.mostion.com/archives/12/ 2023-11-03T11:06:00+08:00 2023-11-03T11:06:00+08:00 Jason http://blog.mostion.com 在用SpringBoot开发后端服务时,我们一般是提供接口给前端使用,但前端通过浏览器调我们接口时,浏览器会有个同源策略的限制,即协议,域名,端口任一不一样时都会导致跨域,这篇文章主要介绍跨域的几种常用解决方案。

测试是否跨域

可以在浏览器中随便打开一个页面的控制台,然后在控制台中执行下面这段代码:

var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8080/user') // 替换请求的方法和地址
xhr.send()
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText)
    }
}

如果出现了如下的输出,代表确实有跨域

WX20231103-104337@2x.png

一、SpringBoot 配置 CORS 解决跨域

即在我们所有响应头配置允许跨域访问,CORS也已经成为主流的跨域解决方案。

  1. 在项目中创建一个新的配置文件
  2. 添加@Configuration注解实现WebMvcConfigurer接口
  3. 重写addCorsMappings方法并设置允许跨域的代码

具体代码如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


// 或者这样, 与springboot 版本有关
@Configuration
public class MyCorsFilter {
    @Bean
    public CorsFilter corsFilter() {
        // 1.创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 支持域
        config.addAllowedOriginPattern("*");
        // 是否发送 Cookie
        config.setAllowCredentials(true);
        // 支持请求方式
        config.addAllowedMethod("*");
        // 允许的原始请求头部信息
        config.addAllowedHeader("*");
        // 暴露的头部信息
        config.addExposedHeader("*");
        // 2.添加地址映射
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        // 3.返回 CorsFilter 对象
        return new CorsFilter(corsConfigurationSource);
    }
}

二、SpringBoot 通过 CorsFilter 解决跨域

这种方式和上面的方式类似,也是通过Java Config的方式配置跨域访问,具体代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class MyCorsFilter {
    @Bean
    public CorsFilter corsFilter() {
        // 1.创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 支持域
        config.addAllowedOriginPattern("*");
        // 是否发送 Cookie
        config.setAllowCredentials(true);
        // 支持请求方式
        config.addAllowedMethod("*");
        // 允许的原始请求头部信息
        config.addAllowedHeader("*");
        // 暴露的头部信息
        config.addExposedHeader("*");
        // 2.添加地址映射
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        // 3.返回 CorsFilter 对象
        return new CorsFilter(corsConfigurationSource);
    }
}

三、SpringBoot 通过注解解决跨域

可以在我们的控制器类或控制器方法上添加,添加在类上表示里面所有方法都可跨域,添加在方法上表示指定方法可以跨域,具体代码如下:

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @GetMapping
    public String getAll() {
        return "成功";
    }
}

四、通过 nginx 配置 CORS 解决跨域

如果我们项目有用 nginx 做反向代理服务器时,也可以在nginx中配置CORS来解决跨域,配置示例如下:

1. 允许全部域名

server {
    ...
    location / {
        #允许 所有头部 所有域 所有方法
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}

2. 允许指定域名

map $http_origin $corsHost {
    default 0;
    "~https://aa.cn" https://aa.cn;
    "~https://bb.cn" https://bb.cn;
    "~https://cc.cn" https://cc.cn;
}
server {
    ...
    location / {
        #允许 所有头部 所有$corsHost域 所有方法
        add_header 'Access-Control-Allow-Origin' $corsHost;
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}
以上就是SpringBoot项目常用的几种解决跨域的方式!
]]>