06.自定义拦截器、全局异常处理类、异步调用

本文深入探讨了Spring框架中的三个关键组件:自定义拦截器、全局异常处理和异步调用。通过具体代码示例,详细讲解了如何实现请求拦截、统一异常管理和异步任务执行,为开发者提供了一个全面理解Spring框架核心机制的视角。
自定义拦截器
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
@Configuration
public class MyInterceptor extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor inter = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("request:"+request.getRequestURL());
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

            }
        };
        registry.addInterceptor(inter).addPathPatterns("/**");
    }
}
全局异常处理类
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Map<String,Object> handleException(Exception e){
        Map<String, Object> map = new HashMap<>();
        map.put("errorCode",500);
        map.put("errorMsg",e.toString());
        return map;
    }
}
异步调用
@SpringBootApplication(scanBasePackages = {"com.fly"})
@EnableAsync
public class SpringDemoApp{

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.Future;

@Service
public class AsyncServiceImpl {
    private static Random random = new Random();

    @Async
    public Future<String> doTask1() throws Exception{
        System.out.println("doTask1 start");
        long b = System.currentTimeMillis();
        Thread.sleep(random.nextInt(1000));
        long e = System.currentTimeMillis();
        System.out.println("doTask1 end:"+(e-b));
        return new AsyncResult<>("doTask1 end");
    }

    @Async
    public Future<String> doTask2() throws Exception{
        System.out.println("doTask2 start");
        long b = System.currentTimeMillis();
        Thread.sleep(random.nextInt(1000));
        long e = System.currentTimeMillis();
        System.out.println("doTask2 end:"+(e-b));
        return new AsyncResult<>("doTask2 end");
    }

    @Async
    public Future<String> doTask3() throws Exception{
        System.out.println("doTask3 start");
        long b = System.currentTimeMillis();
        Thread.sleep(random.nextInt(1000));
        long e = System.currentTimeMillis();
        System.out.println("doTask3 end:"+(e-b));
        return new AsyncResult<>("doTask3 end");
    }
}
 @Autowired
    private AsyncServiceImpl asyncService;

    @RequestMapping("/asyn")
    public String asyn() throws Exception {
        long b = System.currentTimeMillis();
        Future<String> f1 = asyncService.doTask1();
        Future<String> f2 = asyncService.doTask2();
        Future<String> f3 = asyncService.doTask3();
        while (true){
            if (f1.isDone()&&f2.isDone()&&f3.isDone()){
                break;
            }
        }
        long e = System.currentTimeMillis();
        return "asyn end:"+(e-b);
        //doTask2 start
        //doTask1 start
        //doTask3 start
        //doTask1 end:290
        //doTask2 end:607
        //doTask3 end:795

        //"asyn end:802"
    }

转载于:https://www.cnblogs.com/fly-book/p/11573332.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值