网关配置
认证安全
安全主要是解决跨域问题和csrf验证问题,这在OAuth中有具体说明。
创建WebSecurityConfig:
package com.shareprog.zuul.config.security;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @ClassName: SecurityConfig
* @Description: 网关请求权限设置
* @author cl
* @date 2021年1月18日
*/
@EnableWebSecurity
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
;
}
}
创建ZuulConfiguration:
package com.shareprog.zuul.config;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
/**
* @ClassName: ZuulConfig
* @Description: 网关配置
* @author cl
* @date 2021年1月18日
*/
@Configuration
public class ZuulConfiguration {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
// 预检请求的有效期,单位为秒
configuration.setMaxAge(3600L);
// 允许跨域访问的域名
configuration.setAllowedOrigins(Collections.singletonList("*"));
//允许的请求方法
configuration.setAllowedMethods(Collections.singletonList("*"));
// 是否支持安全证书
configuration.setAllowCredentials(true);
// 允许的请求头
configuration.setAllowedHeaders(Collections.singletonList("*"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Hystrix
分布式系统环境下,服务间类似依赖非常常见,一个业务调用通常依赖多个基础服务。当某个服务不可用时,依赖的服务请求线程被阻塞,当有大批量请求调用不可用的服务时,最终可能导致整个依赖的服务资源耗尽,无法继续对外提供服务。并且这种不可用可能沿请求调用链向上传递,这种现象被称为雪崩效应。
Hystrix 可以让我们在分布式系统中对服务间的调用进行控制,加入一些调用延迟或者依赖故障的容错机制。Hystrix 通过将依赖服务进行资源隔离,进而阻止某个依赖服务出现故障时在整个系统所有的依赖服务调用中进行蔓延;同时Hystrix 还提供故障时的 fallback 降级机制。
在ZuulConfiguration添加Hystrix配置,添加后代码如下:
package com.shareprog.zuul.config;
import java.util.Collections;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import com.shareprog.zuul.config.hystrix.ZuulFallbackProvider;
/**
* @ClassName: ZuulConfig
* @Description: 网关配置
* @author cl
* @date 2021年1月18日
*/
@Configuration
public class ZuulConfiguration {
/**
* <p>Title: getServlet</p>
* <p>Description: 此配置是为了服务监控而配置,与服务容错本身无关,
* ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream"
* 只要在自己的项目里配置上下面的servlet就可以了</p>
* @return
*/
@Bean
public ServletRegistrationBean<HystrixMetricsStreamServlet> getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
@Bean
public ZuulFallbackProvider zuulFallbackProvider() {
return new ZuulFallbackProvider();
}
}
接着创建ZuulFallbackProvider,设置熔断器处理方法,这里打印日志仅用于排查问题用。
package com.shareprog.zuul.config.hystrix;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.client.ClientHttpResponse;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: ZuulFallbackProvider
* @Description: 熔断器处理方法
* @author cl
* @date 2021年1月18日
*/
@Slf4j
public class ZuulFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
return "*";
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
log.info("路由地址: {}", route);
log.info("异常信息:{}:", cause.getMessage());
return new ZuulClientHttpResponse();
}
}
过滤器熔断进行处理方法,代码如下:
package com.shareprog.zuul.config.hystrix;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: ZuulClientHttpResponse
* @Description: 熔断器降级处理
* @author cl
* @date 2021年1月18日
*/
@Slf4j
public class ZuulClientHttpResponse implements ClientHttpResponse {
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("对不起,该服务无法获取".getBytes("utf-8"));
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.OK.value();
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.OK.getReasonPhrase();
}
@Override
public void close() {
log.info("请求已关闭!");
}
}
在该过程中需要在application.yml添加配置:
hystrix:
command:
default:
execution:
timeout:
enabled: false
isolation:
thread:
timeoutInMilliseconds: 15000
即默认在15秒后自动熔断,默认是1秒。