Skip to content

Instantly share code, notes, and snippets.

@fitzoh
Created September 7, 2017 01:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fitzoh/5949ad29496ef8015ebb060c6d10e941 to your computer and use it in GitHub Desktop.
Save fitzoh/5949ad29496ef8015ebb060c6d10e941 to your computer and use it in GitHub Desktop.
Canary deploys with spring-cloud-gateway (2.0.0-M1)
@EnableGateway
@SpringBootApplication
public class SpringCloudGatewayApplication {
private final String cookieName = "beta_active";
private final String headerName = "X-Beta-active";
private final String betaActiveValue = "true";
/**
* They're in the beta if they have a cookie or request header set
*/
private final Predicate<ServerWebExchange> ifBetaActive = serverWebExchange -> {
HttpCookie cookie = serverWebExchange.getRequest().getCookies().getFirst(cookieName);
if (cookie != null && Objects.equals(cookie.getValue(), betaActiveValue)) {
return true;
}
List<String> values = serverWebExchange.getRequest().getHeaders().get(headerName);
return values != null && values.contains(betaActiveValue);
};
/**
* 10% chance that we'll enroll them in the beta
*/
private final Predicate<ServerWebExchange> randomBetaEnroll = serverWebExchange -> Math.random() < 0.2;
/**
* this always returns true
*/
private final Predicate<ServerWebExchange> always = (x) -> true;
/**
* Adds a cookie to the response so they stay in the beta
*/
private final WebFilter addBetaCookieFilter = (ServerWebExchange exchange, WebFilterChain chain) -> {
exchange.getResponse().addCookie(ResponseCookie.from(cookieName, betaActiveValue).maxAge(Duration.ofHours(4)).httpOnly(true).build());
return chain.filter(exchange);
};
public static void main(String[] args) {
SpringApplication.run(SpringCloudGatewayApplication.class, args);
}
@Bean
public RouteLocator routes() {
return Routes.locator()
.route("new-service")
.uri("http://localhost:9002")
.predicate(ifBetaActive.or(randomBetaEnroll))
.add(addBetaCookieFilter)
.and()
.route("old-service")
.uri("http://localhost:9001")
.predicate(always)
.and()
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment