第一步,定义一个实体User:

@Data
public class User {
    private Long id;
    private String name;
    private Date registerDate;
}
复制代码

第二步,实现Converter接口

public class DateConverter implements Converter {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Date convert(String source) {
        if (source != null && !"".equals(source)) {
            try {
                simpleDateFormat.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
复制代码

第三步,将新定义的类型转换器注入到spring容器中:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }
}
复制代码

第四步,调用接口

@RequestMapping("/user")
@RestController
public class UserController {
    @RequestMapping("/save")
    public String save(@RequestBody User user) {
        return "success";
    }
}
复制代码

请求接口时User对象中registerDate字段会被自动转换成Date类型。

六 spring mvc拦截器,用过的都说好

spring mvc拦截器根spring拦截器相比,它里面能够获取HttpServletRequest和HttpServletResponse 等web对象实例。

spring mvc拦截器的顶层接口是:HandlerInterceptor,包含三个方法:

为了方便我们一般情况会用HandlerInterceptor接口的实现类HandlerInterceptorAdapter类。

假如有权限认证、日志、统计的场景,可以使用该拦截器。

第一步,继承HandlerInterceptorAdapter类定义拦截器:

@Service
public class AService {
    @PostConstruct
    public void init() {
        System.out.println("===初始化===");
    }
}
复制代码

第二步,将该拦截器注册到spring容器:

@Configuration
public class WebAuthConfig extends WebMvcConfigurerAdapter {
 
    @Bean
    public AuthInterceptor getAuthInterceptor() {
        return new AuthInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getAuthInterceptor());
    }
}
复制代码

第三步,在请求接口时spring mvc通过该拦截器,能够自动拦截该接口,并且校验权限。

该拦截器其实相对来说,比较简单,可以在DispatcherServlet类的doDispatch方法中看到调用过程:

转换器转换器_代码转换器_代码转换器的设计与实现

顺便说一句,这里只讲了spring mvc的拦截器,并没有讲spring的拦截器,是因为我有点小私心,后面就会知道。

七 Enable开关真香

不知道你有没有用过Enable开头的注解,比如:EnableAsync、EnableCaching、EnableAspectJAutoProxy等,这类注解就像开关一样,只要在@Configuration定义的配置类上加上这类注解,就能开启相关的功能。

是不是很酷?

让我们一起实现一个自己的开关:

第一步,定义一个LogFilter:

@Service
public class BService implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("===初始化===");
    }
}
复制代码

第二步,注册LogFilter:

@ConditionalOnWebApplication
public class LogFilterWebConfig {
    @Bean
    public LogFilter timeFilter() {
        return new LogFilter();
    }
}
复制代码

注意,这里用了@ConditionalOnWebApplication注解,没有直接使用@Configuration注解。

第三步,定义开关@EnableLog注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(LogFilterWebConfig.class)
public @interface EnableLog {
}
复制代码

第四步,只需在springboot启动类加上@EnableLog注解即可开启LogFilter记录请求和响应日志的功能。

八 RestTemplate拦截器的春天

我们使用RestTemplate调用远程接口时,有时需要在header中传递信息,比如:traceId,source等,便于在查询日志时能够串联一次完整的请求链路代码转换器,快速定位问题。

这种业务场景就能通过ClientHttpRequestInterceptor接口实现,具体做法如下:

第一步,实现ClientHttpRequestInterceptor接口:

public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set("traceId", MdcUtil.get());
        return execution.execute(request, body);
    }
}
复制代码

第二步,定义配置类:

@Configuration
public class RestTemplateConfiguration {
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));
        return restTemplate;
    }
    @Bean
    public RestTemplateInterceptor restTemplateInterceptor() {
        return new RestTemplateInterceptor();
    }
}
复制代码

其中MdcUtil其实是利用MDC工具在ThreadLocal中存储和获取traceId

public class MdcUtil {
    private static final String TRACE_ID = "TRACE_ID";
    public static String get() {
        return MDC.get(TRACE_ID);
    }
    public static void add(String value) {
        MDC.put(TRACE_ID, value);
    }
}
复制代码

当然,这个例子中没有演示MdcUtil类的add方法具体调的地方,我们可以在filter中执行接口方法之前代码转换器,生成traceId,调用MdcUtil类的add方法添加到MDC中,然后在同一个请求的其他地方就能通过MdcUtil类的get方法获取到该traceId。

九 统一异常处理

以前我们在开发接口时,如果出现异常,为了给用户一个更友好的提示,例如:

@RequestMapping("/test")
@RestController
public class TestController {
    @GetMapping("/add")
    public String add() {
        int a = 10 / 0;
        return "成功";
    }
}
复制代码

如果不做任何处理请求add接口结果直接报错:

转换器转换器_代码转换器的设计与实现_代码转换器

what?用户能直接看到错误信息?

这种交互方式给用户的体验非常差,为了解决这个问题,我们通常会在接口中捕获异常:

@GetMapping("/add")
public String add() {
        String result = "成功";
        try {
            int a = 10 / 0;
        } catch (Exception e) {
            result = "数据异常";
        }
        return result;
}
复制代码

接口改造后,出现异常时会提示:“数据异常”,对用户来说更友好。

看起来挺不错的,但是有问题。。。

如果只是一个接口还好,但是如果项目中有成百上千个接口,都要加上异常捕获代码吗?

答案是否定的,这时全局异常处理就派上用场了:RestControllerAdvice。

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        if (e instanceof ArithmeticException) {
            return "数据异常";
        }
        if (e instanceof Exception) {
            return "服务器内部异常";
        }
        retur nnull;
    }
}
复制代码

只需在handleException方法中处理异常情况,业务接口中可以放心使用,不再需要捕获异常(有人统一处理了)。真是爽歪歪。

十 异步也可以这么优雅

以前我们在使用异步功能时,通常情况下有三种方式:

让我们一起回顾一下:

继承Thread类

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("===call MyThread===");
    }
    public static void main(String[] args) {
        new MyThread().start();
    }
}
复制代码

实现Runable接口

public class MyWork implements Runnable {
    @Override
    public void run() {
        System.out.println("===call MyWork===");
    }
    public static void main(String[] args) {
        new Thread(new MyWork()).start();
    }
}
复制代码

使用线程池

public class MyThreadPool {
    private static ExecutorService executorService = new ThreadPoolExecutor(1, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(200));
    static class Work implements Runnable {
        @Override
        public void run() {
            System.out.println("===call work===");
        }
    }
    public static void main(String[] args) {
        try {
            executorService.submit(new MyThreadPool.Work());
        } finally {
            executorService.shutdown();
        }
    }
}
复制代码

这三种实现异步的方法不能说不好,但是spring已经帮我们抽取了一些公共的地方,我们无需再继承Thread类或实现Runable接口,它都搞定了。

如何spring异步功能呢?

第一步,springboot项目启动类上加@EnableAsync注解。

@EnableAsync
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);
    }
}
复制代码

第二步,在需要使用异步的方法上加上@Async注解:

@Service
public class PersonService {
    @Async
    public String get() {
        System.out.println("===add==");
        return "data";
    }
}
复制代码

然后在使用的地方调用一下:personService.get();就拥有了异步功能,是不是很神奇。

默认情况下营销引流,spring会为我们的异步方法创建一个线程去执行,如果该方法被调用次数非常多的话,需要创建大量的线程,会导致资源浪费。

这时,我们可以定义一个线程池,异步方法将会被自动提交到线程池中执行。

@Configuration
public class ThreadPoolConfig {
    @Value("${thread.pool.corePoolSize:5}")
    private int corePoolSize;
    @Value("${thread.pool.maxPoolSize:10}")
    private int maxPoolSize;
    @Value("${thread.pool.queueCapacity:200}")
    private int queueCapacity;
    @Value("${thread.pool.keepAliveSeconds:30}")
    private int keepAliveSeconds;
    @Value("${thread.pool.threadNamePrefix:ASYNC_}")
    private String threadNamePrefix;
    @Bean
    public Executor MessageExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
复制代码

spring异步的核心方法:

转换器转换器_代码转换器的设计与实现_代码转换器

根据返回值不同,处理情况也不太一样,具体分为如下情况:

代码转换器的设计与实现_转换器转换器_代码转换器

十一 听说缓存好用,没想到这么好用

spring cache架构图:

代码转换器的设计与实现_代码转换器_转换器转换器

它目前支持多种缓存:

代码转换器的设计与实现_代码转换器_转换器转换器

我们在这里以caffeine为例,它是spring官方推荐的。

第一步,引入caffeine的相关jar包


    org.springframework.boot
    spring-boot-starter-cache


    com.github.ben-manes.caffeine
    caffeine
    2.6.0

复制代码

第二步,配置CacheManager,开启EnableCaching

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager(){
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        //Caffeine配置
        Caffeine caffeine = Caffeine.newBuilder()
                //最后一次写入后经过固定时间过期
                .expireAfterWrite(10, TimeUnit.SECONDS)
                //缓存的最大条数
                .maximumSize(1000);
        cacheManager.setCaffeine(caffeine);
        return cacheManager;
    }
}
复制代码

第三步,使用Cacheable注解获取数据

@Service
public class CategoryService {
   
   //category是缓存名称,#type是具体的key,可支持el表达式
   @Cacheable(value = "category", key = "#type")
   public CategoryModel getCategory(Integer type) {
       return getCategoryByType(type);
   }
   private CategoryModel getCategoryByType(Integer type) {
       System.out.println("根据不同的type:" + type + "获取不同的分类数据");
       CategoryModel categoryModel = new CategoryModel();
       categoryModel.setId(1L);
       categoryModel.setParentId(0L);
       categoryModel.setName("电器");
       categoryModel.setLevel(3);
       return categoryModel;
   }
}
复制代码

调用categoryService.getCategory()方法时,先从caffine缓存中获取数据,如果能够获取到数据则直接返回该数据,不会进入方法体。如果不能获取到数据,则直接方法体中的代码获取到数据,然后放到caffine缓存中。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注