话不多说,直接贴码:
需要的jar
<!-- zuul限流 -->
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
</dependencies>
配置:
zuul:
routes:
api-a: #id
path: /api-a/** #路径
serviceId: EURKA-CLIENT1 #子服务id
api-b:
path: /api-b/**
serviceId: EURKA-CLIENT131/
###限流
ratelimit:
enabled: true #开启限流
repository: redis #限流内容存储介质
default-policy:#以下配置说明,3秒中只能有一次请求,且请求总时间不能超过1秒
limit: 1
quota: 1
refresh-interval: 3
policies: #指定特殊子服务进行配置
EURKA-CLIENT1: #字符id
limit: 10
quota: 50
refresh-interval: 60
type: url
要想具体了解限流可以参照https://mp.csdn.net/postedit/86711784这篇文章
熔断,是zuul自己的,项目中增加如下类,一切ok
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import com.google.gson.JsonObject;
/**
* @author 王峰
* @Time:2019年1月29日 下午4:14:23
* @version 1.0
* zuul 断路反馈,比如路由指定的子服务没有启动报错,我们可以把错误信息进行包装在反馈给消费者
*
*
*/
@Component
public class ApiFallbackProvider implements FallbackProvider{
@Override
public String getRoute() {
return "*";//在此可以指定对应子服务的id,如果是全部用*或者null
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable throwable) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {JSONObject r = new JSONObject();
try {
r.put("state", "9999");
r.put("msg", "系统错误,请求失败");
} catch (JSONException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(r.toString().getBytes("UTF-8"));}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
//和body中的内容编码一致,否则容易乱码
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
};
}}
至此路由这块的完成