Reputation: 6036
I have a simple Spring Cloud Netflix Zuul in front of my services. I would like to set rate limiting for all requests coming to this Zuul.
I have seen this post: https://www.baeldung.com/spring-cloud-zuul-rate-limit However I have neither controllers in my Zuul or JPA repository. All routes Zuul receives from Eureka.
Zuul:
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class BlitzZuulApplication {
public static void main(String[] args) {
SpringApplication.run(BlitzZuulApplication.class, args);
}
}
application.properties:
spring.application.name=zuul
server.port = 7125
my.eureka.port=7126eureka.client.service-url.defaultZone=http://localhost:${my.eureka.port}/eureka
pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit-core</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
How to configure Zuul for rate limiting and restrict the number of overall incoming requests?
Upvotes: 0
Views: 5514
Reputation: 6036
I use the following application.yaml file:
zuul:
routes:
my-service:
path: /
ratelimit:
enabled: true
repository: JPA
policy-list:
my-service:
- limit: 2
refresh-interval: 60
type:
- origin
strip-prefix: true
At this point property zuul.ratelimit.repository should be not empty. There is some options listed if you miss it.
I start using JPA repository. For this spring-boot-starter-data-jpa dependency should be added in a project and datasource should be configured as usual.
If you now start a project you will get this Exception:
java.sql.SQLSyntaxErrorException: Table 'rate' doesn't exist
In this source you can find Rate.java class in config folder with a structure: https://www.programcreek.com/java-api-examples/?code=marcosbarbero/spring-cloud-zuul-ratelimit/spring-cloud-zuul-ratelimit-master/spring-cloud-zuul-ratelimit-core/src/main/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/RateLimitAutoConfiguration.java#
So Rate entity is:
@Entity
public class Rate {
@Id
private String key;
private Long remaining;
private Long remainingQuota;
private Long reset;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private Date expiration;
// constructor, getters and setters
}
With this configuration and creating the table all works fine, Zuul saves information about request in the table. In my case 2 requests allowed in 60 seconds.
Upvotes: 3