Created
September 7, 2017 01:24
-
-
Save fitzoh/5949ad29496ef8015ebb060c6d10e941 to your computer and use it in GitHub Desktop.
Canary deploys with spring-cloud-gateway (2.0.0-M1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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