一、拦截器
建立一个拦截器的类
@Configuration//声明是一个配置
public class MyInterceptor extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor=new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("我的拦截器...");
return true;
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
};
registry.addInterceptor(interceptor).addPathPatterns("/**");//拦截所有
}
}
二、异步调用,springApplication.java里的类前面加上@EnableAsync //允许异步执行
先定义一个接口
public interface AsyncService {
Future<String> doTask1() throws Exception;
Future<String> doTask2() throws Exception;
Future<String> doTask3() throws Exception;
}
实现接口
@Service //告诉springboot我是一个服务类
public class AsyncServiceImp1 implements AsyncService {
private static Random random=new Random();
@Async //加上之后允许异步执行
@Override
public Future<String> doTask1() throws Exception {
// TODO Auto-generated method stub
System.out.println("任务1开始执行");
long start=System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end=System.currentTimeMillis();
System.out.print(end-start+" ms");
return new AsyncResult<String>("任务1结束");
}
@Async
@Override
public Future<String> doTask2() throws Exception {
System.out.println("任务2开始执行");
long start=System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end=System.currentTimeMillis();
System.out.print(end-start+" ms");
return new AsyncResult<String>("任务2结束");
}
@Async
@Override
public Future<String> doTask3() throws Exception {
System.out.println("任务3开始执行");
long start=System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end=System.currentTimeMillis();
System.out.print(end-start+" ms");
return new AsyncResult<String>("任务3结束");
}
}
访问调用
@Controller
public class testController {
@Autowired
private AsyncService asyncService;
@RequestMapping("/async")
@ResponseBody
public String asyncTest() throws Exception{
long start=System.currentTimeMillis();
Future<String> task1=asyncService.doTask1();
Future<String> task2=asyncService.doTask2();
Future<String> task3=asyncService.doTask3();
while(true){
if(task1.isDone()&&task2.isDone()&&task3.isDone())
break;
Thread.sleep(1000);
}
long end=System.currentTimeMillis();
return "全部结束"+(end-start);
}
}