MvcConfig.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.yihu.jw.config.mvc;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.web.client.RestTemplateBuilder;
  4. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.web.client.RestTemplate;
  8. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  9. import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
  10. import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
  11. /**
  12. * Created by chenweida on 2017/6/15.
  13. */
  14. @Configuration
  15. public class MvcConfig extends WebMvcConfigurationSupport {
  16. /**
  17. * 全局异常定义
  18. * @return
  19. */
  20. @Bean
  21. public GlobalHandlerExceptionResolver globalHandlerExceptionResolver() {
  22. return new GlobalHandlerExceptionResolver();
  23. }
  24. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  25. registry.addResourceHandler("swagger-ui.html")
  26. .addResourceLocations("classpath:/META-INF/resources/");
  27. registry.addResourceHandler("/webjars/**")
  28. .addResourceLocations("classpath:/META-INF/resources/webjars/");
  29. }
  30. @Bean
  31. @LoadBalanced
  32. // 添加负载均衡支持,很简单,只需要在RestTemplate上添加@LoadBalanced注解,那么RestTemplate即具有负载均衡的功能,如果不加@LoadBalanced注解的话,会报java.net.UnknownHostException:springboot-h2异常,此时无法通过注册到Eureka Server上的服务名来调用服务,因为RestTemplate是无法从服务名映射到ip:port的,映射的功能是由LoadBalancerClient来实现的。
  33. public RestTemplate restTemplate() {
  34. return new RestTemplate();
  35. }
  36. }