Browse Source

Fix up sample for 1.0

pull/53/merge
Dave Syer 7 years ago
parent
commit
ee18259df7
  1. 0
      spring-cloud-gateway-sample/.jdk8
  2. 9
      spring-cloud-gateway-sample/pom.xml
  3. 69
      spring-cloud-gateway-sample/src/main/java/org/springframework/cloud/gateway/sample/GatewaySampleApplication.java
  4. 61
      spring-cloud-gateway-sample/src/main/java/org/springframework/cloud/gateway/sample/ThrottleWebFilterFactory.java
  5. 32
      spring-cloud-gateway-sample/src/main/resources/application.yml
  6. 48
      spring-cloud-gateway-sample/src/test/java/org/springframework/cloud/gateway/sample/GatewaySampleApplicationTests.java

0
spring-cloud-gateway-sample/.jdk8

9
spring-cloud-gateway-sample/pom.xml

@ -5,7 +5,6 @@ @@ -5,7 +5,6 @@
<groupId>org.springframework.cloud.gateway</groupId>
<artifactId>spring-cloud-gateway-sample</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Gateway Sample</name>
@ -18,9 +17,6 @@ @@ -18,9 +17,6 @@
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<properties>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -30,6 +26,11 @@ @@ -30,6 +26,11 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-mvc</artifactId>
</dependency>
<dependency>
<groupId>org.isomorphism</groupId>
<artifactId>token-bucket</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

69
spring-cloud-gateway-sample/src/main/java/org/springframework/cloud/gateway/sample/GatewaySampleApplication.java

@ -17,55 +17,44 @@ @@ -17,55 +17,44 @@
package org.springframework.cloud.gateway.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.gateway.EnableGateway;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.Routes;
import org.springframework.context.annotation.Bean;
import java.net.URI;
import java.util.function.Function;
import static org.springframework.cloud.gateway.filter.factory.WebFilterFactories.addResponseHeader;
import static org.springframework.cloud.gateway.handler.predicate.RoutePredicates.host;
import static org.springframework.cloud.gateway.handler.predicate.RoutePredicates.path;
import static org.springframework.tuple.TupleBuilder.tuple;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Spencer Gibb
* @author Dave Syer
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableGateway
@RestController
@SpringBootApplication
public class GatewaySampleApplication {
@Bean
public RouteLocator customRouteLocator(ThrottleWebFilterFactory throttle) {
return Routes.locator()
.route("test")
.uri("http://httpbin.org:80")
.predicate(host("**.abc.org").and(path("/image/png")))
.addResponseHeader("X-TestHeader", "foobar")
.and()
.route("test2")
.uri("http://httpbin.org:80")
.predicate(path("/image/webp"))
.add(addResponseHeader("X-AnotherHeader", "baz"))
.and()
.route("test3")
.order(-1)
.uri("http://httpbin.org:80")
.predicate(host("**.throttle.org").and(path("/get")))
.add(throttle.apply(tuple().of("capacity", 1,
"refillTokens", 1,
"refillPeriod", 10,
"refillUnit", "SECONDS")))
.and()
.build();
@Value("${remote.home}")
private URI home;
@GetMapping(path="/test", headers="x-host=png.abc.org")
public ResponseEntity<Object> proxy(ProxyExchange<Object> proxy) throws Exception {
return proxy.uri(home.toString() + "/image/png")
.get(header("X-TestHeader", "foobar"));
}
@GetMapping("/test2")
public ResponseEntity<Object> proxyFoos(ProxyExchange<Object> proxy) throws Exception {
return proxy.uri(home.toString() + "/image/webp").get(header("X-AnotherHeader", "baz"));
}
@Bean
public ThrottleWebFilterFactory throttleWebFilterFactory() {
return new ThrottleWebFilterFactory();
private Function<ResponseEntity<Object>, ResponseEntity<Object>> header(String key,
String value) {
return response -> ResponseEntity.status(response.getStatusCode())
.headers(response.getHeaders()).header(key, value)
.body(response.getBody());
}
public static void main(String[] args) {

61
spring-cloud-gateway-sample/src/main/java/org/springframework/cloud/gateway/sample/ThrottleWebFilterFactory.java

@ -1,61 +0,0 @@ @@ -1,61 +0,0 @@
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.cloud.gateway.sample;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.isomorphism.util.TokenBucket;
import org.isomorphism.util.TokenBuckets;
import org.springframework.cloud.gateway.filter.factory.WebFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.tuple.Tuple;
import org.springframework.web.server.WebFilter;
import java.util.concurrent.TimeUnit;
/**
* Sample throttling filter.
* See https://github.com/bbeck/token-bucket
*/
public class ThrottleWebFilterFactory implements WebFilterFactory {
private Log log = LogFactory.getLog(getClass());
@Override
public WebFilter apply(Tuple args) {
int capacity = args.getInt("capacity");
int refillTokens = args.getInt("refillTokens");
int refillPeriod = args.getInt("refillPeriod");
TimeUnit refillUnit = TimeUnit.valueOf(args.getString("refillUnit"));
final TokenBucket tokenBucket = TokenBuckets.builder()
.withCapacity(capacity)
.withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit)
.build();
return (exchange, chain) -> {
//TODO: get a token bucket for a key
log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
boolean consumed = tokenBucket.tryConsume();
if (consumed) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
};
}
}

32
spring-cloud-gateway-sample/src/main/resources/application.yml

@ -1,29 +1,5 @@ @@ -1,29 +1,5 @@
test:
hostport: httpbin.org:80
# hostport: localhost:5000
uri: http://${test.hostport}
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
routes:
# =====================================
- id: default_path_to_httpbin
uri: ${test.uri}
order: 10000
predicates:
- Path=/**
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
management:
context-path: /admin
# port: 8081
security:
enabled: false
remote:
home: http://httpbin.org

48
spring-cloud-gateway-sample/src/test/java/org/springframework/cloud/gateway/sample/GatewaySampleApplicationTests.java

@ -17,20 +17,18 @@ @@ -17,20 +17,18 @@
package org.springframework.cloud.gateway.sample;
import org.junit.Before;
import java.net.URI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpHeaders;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@ -39,34 +37,26 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @@ -39,34 +37,26 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GatewaySampleApplication.class, webEnvironment = RANDOM_PORT)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class GatewaySampleApplicationTests {
@LocalServerPort
protected int port = 0;
protected WebClient webClient;
protected String baseUri;
@Autowired
protected TestRestTemplate rest;
@Before
public void setup() {
baseUri = "http://localhost:" + port;
this.webClient = WebClient.create(baseUri);
@Test
public void passthru() {
assertThat(rest.getForEntity("/test2", byte[].class).getStatusCode())
.isEqualTo(HttpStatus.OK);
}
@Test
public void contextLoads() {
Mono<ClientResponse> result = webClient.get()
.uri("/get")
.exchange();
StepVerifier.create(result)
.consumeNextWith(
response -> {
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
HttpHeaders httpHeaders = response.headers().asHttpHeaders();
})
.expectComplete()
.verify(Duration.ofSeconds(5));
public void header() throws Exception {
assertThat(rest
.exchange(RequestEntity.get(new URI("/test"))
.header("x-host", "png.abc.org").build(), byte[].class)
.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}

Loading…
Cancel
Save