1. Overview
1.概述
In this tutorial, we’ll have a look at Flips, a library that implements feature flags in the form of powerful annotations for Spring Core, Spring MVC, and Spring Boot applications.
在本教程中,我们将看看Flips,这个库以强大的注释形式为Spring Core、Spring MVC和Spring Boot应用程序实现功能标志。
Feature flags (or toggles) are a pattern for delivering new features quickly and safely. These toggles allow us to modify application behavior without changing or deploying new code. Martin Fowler’s blog has a very informative article about feature flags here.
功能标志(或称切换器)是一种快速、安全地提供新功能的模式。这些切换器使我们能够在不改变或部署新代码的情况下修改应用程序的行为。Martin Fowler 的博客中有一篇关于功能标志的信息量很大的文章这里。
2. Maven Dependency
2.Maven的依赖性
Before we get started, we need to add the Flips library to our pom.xml:
在我们开始之前,我们需要将Flips库添加到我们的pom.xml中:。
<dependency>
<groupId>com.github.feature-flip</groupId>
<artifactId>flips-core</artifactId>
<version>1.0.1</version>
</dependency>
Maven Central has the latest version of the library, and the Github project is here.
Maven Central有最新版本的库,而Github项目在这里。
Of course, we also need to include a Spring:
当然,我们还需要包括一个Spring。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
Since Flips isn’t yet compatible with Spring version 5.x, we’re going to use the latest version of Spring Boot in the 4.x branch.
由于Flips还不兼容Spring 5.x版本,我们将使用4.x分支中的最新版本的Spring Boot。
3. A Simple REST Service for Flips
3.用于翻转的简单REST服务
Let’s put together a simple Spring Boot project for adding and toggling new features and flags.
让我们把一个简单的Spring Boot项目放在一起,用于添加和切换新功能和标志。
Our REST application will provide access to Foo resources:
我们的REST应用程序将提供对Foo资源的访问。
public class Foo {
private String name;
private int id;
}
We’ll simply create a Service that maintains a list of Foos:
我们将简单地创建一个Service,维护一个Foos的列表。
@Service
public class FlipService {
private List<Foo> foos;
public List<Foo> getAllFoos() {
return foos;
}
public Foo getNewFoo() {
return new Foo("New Foo!", 99);
}
}
We’ll refer to additional service methods as we go, but this snippet should be enough to illustrate what FlipService does in the system.
我们会在进行中参考其他的服务方法,但这个片段应该足以说明FlipService在系统中的作用。
And of course, we need to create a Controller:
当然,我们还需要创建一个控制器。
@RestController
public class FlipController {
private FlipService flipService;
// constructors
@GetMapping("/foos")
public List<Foo> getAllFoos() {
return flipService.getAllFoos();
}
}
4. Control Features Based on Configuration
4.基于配置的控制功能
The most basic use of Flips is to enable or disable a feature based on configuration. Flips has several annotations for this.
Flips最基本的用途是根据配置来启用或禁用一个功能。Flips有几个注释用于此。
4.1. Environment Property
4.1.环境属性
Let’s imagine we added a new capability to FlipService; retrieving Foos by their id.
让我们设想一下,我们为FlipService添加了一项新的功能;通过他们的id来检索Foos。
Let’s add the new request to the controller:
让我们把新的请求添加到控制器中。
@GetMapping("/foos/{id}")
@FlipOnEnvironmentProperty(
property = "feature.foo.by.id",
expectedValue = "Y")
public Foo getFooById(@PathVariable int id) {
return flipService.getFooById(id)
.orElse(new Foo("Not Found", -1));
}
The @FlipOnEnvironmentProperty controls whether or not this API is available.
@FlipOnEnvironmentProperty控制该API是否可用。
Simply put, when feature.foo.by.id is Y, we can make requests by Id. If it isn’t (or not defined at all) Flips will disable the API method.
简单地说,当feature.foo.by.id为Y时,我们可以按Id进行请求。如果它不是(或根本没有定义),Flips将禁用该API方法。
If a feature isn’t enabled, Flips will throw FeatureNotEnabledException and Spring will return “Not Implemented” to the REST client.
如果一个功能没有启用,Flips将抛出FeatureNotEnabledException,Spring将向REST客户端返回 “未实施”。
When we call the API with the property set to N, this is what we see:
当我们在属性设置为N的情况下调用API,我们看到的是这样的情况。
Status = 501
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {
"errorMessage": "Feature not enabled, identified by method
public com.baeldung.flips.model.Foo
com.baeldung.flips.controller.FlipController.getFooById(int)",
"className":"com.baeldung.flips.controller.FlipController",
"featureName":"getFooById"
}
As expected, Spring catches the FeatureNotEnabledException and returns status 501 to the client.
正如预期的那样,Spring抓住了FeatureNotEnabledException,并向客户端返回状态501。
4.2. Active Profile
4.2.活动简介
Spring has long given us the ability to map beans to different profiles, such as dev, test, or prod. Expanding on this capability to mapping feature flags to the active profile makes intuitive sense.
长期以来,Spring 为我们提供了将 Bean 映射到不同配置文件的能力,如dev、test或prod。将这一功能扩展到将功能标志映射到活动配置文件中,具有直观的意义。
Let’s see how features are enabled or disabled based on the active Spring Profile:
让我们看看如何根据活动的Spring Profile启用或禁用功能。
@RequestMapping(value = "/foos", method = RequestMethod.GET)
@FlipOnProfiles(activeProfiles = "dev")
public List getAllFoos() {
return flipService.getAllFoos();
}
The @FlipOnProfiles annotation accepts a list of profile names. If the active profile is in the list, the API is accessible.
@FlipOnProfiles注解接受一个配置文件名称的列表。如果活动的配置文件在列表中,则可以访问该API。
4.3. Spring Expressions
4.3.Spring表达式
Spring’s Expression Language (SpEL) is the powerful mechanism for manipulating the runtime environment. Flips has us a way to toggle features with it as well.
Spring的表达式语言(SpEL)是操纵运行时环境的强大机制。Flips也为我们提供了一种用它来切换功能的方法。
@FlipOnSpringExpression toggles a method based on a SpEL expression that returns a boolean.
@FlipOnSpringExpression根据返回布尔值的SpEL表达式来切换一个方法。
Let’s use a simple expression to control a new feature:
让我们用一个简单的表达式来控制一个新功能。
@FlipOnSpringExpression(expression = "(2 + 2) == 4")
@GetMapping("/foo/new")
public Foo getNewFoo() {
return flipService.getNewFoo();
}
4.4. Disable
4.4.禁用
To disable a feature completely, use @FlipOff:
要完全禁用一个功能,请使用@FlipOff。
@GetMapping("/foo/first")
@FlipOff
public Foo getFirstFoo() {
return flipService.getLastFoo();
}
In this example, getFirstFoo() is completely inaccessible.
在这个例子中,getFirstFoo()是完全无法访问的。
As we’ll see below, we can combine Flips annotations, making it possible to use @FlipOff to disable a feature based on the environment or other criteria.
正如我们将在下面看到的,我们可以结合Flips注释,使得使用@FlipOff 来根据环境或其他标准禁用一个功能成为可能。
5. Control Features With Date/Time
5.用日期/时间控制功能
Flips can toggle a feature based on a date/time or the day of the week. Tying the availability of a new feature to the day or date has obvious advantages.
翻转可以根据日期/时间或一周中的某一天来切换一个功能。将一项新功能的可用性与日期挂钩具有明显的优势。
5.1. Date and Time
5.1.日期和时间
@FlipOnDateTime accepts the name of a property that is formatted in ISO 8601 format.
@FlipOnDateTime接受以ISO 8601格式表示的属性名称。
So let’s set a property indicating a new feature that will be active on March 1st:
因此,让我们设置一个表示新功能的属性,它将在3月1日激活。
first.active.after=2018-03-01T00:00:00Z
Then we’ll write an API for retrieving the first Foo:
然后我们将写一个API来检索第一个Foo。
@GetMapping("/foo/first")
@FlipOnDateTime(cutoffDateTimeProperty = "first.active.after")
public Foo getFirstFoo() {
return flipService.getLastFoo();
}
Flips will check the named property. If the property exists and the specified date/time have passed, the feature is enabled.
Flips将检查命名的属性。如果该属性存在并且指定的日期/时间已过,则该功能被启用。
5.2. Day of Week
5.2.一周的日期
The library provides @FlipOnDaysOfWeek, which is useful for operations such as A/B testing:
该库提供了@FlipOnDaysOfWeek,这对A/B测试等操作很有用。
@GetMapping("/foo/{id}")
@FlipOnDaysOfWeek(daysOfWeek={DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY})
public Foo getFooByNewId(@PathVariable int id) {
return flipService.getFooById(id).orElse(new Foo("Not Found", -1));
}
getFooByNewId() is only available on Mondays and Wednesdays.
getFooByNewId()只在周一和周三可用。
6. Replace a Bean
6.替换一个Bean
Switching methods on and off is useful, but we may want to introduce new behavior via new objects. @FlipBean directs Flips to call a method in a new bean.
打开和关闭方法是很有用的,但是我们可能想通过新的对象引入新的行为。@FlipBean指示Flips调用一个新Bean中的方法。
A Flips annotation can work on any Spring @Component. So far, we’ve only modified our @RestController, let’s try modifying our Service.
到目前为止,我们只修改了@RestController,让我们试着修改我们的Service.。
We’ll create a new service with different behavior from FlipService:
我们将创建一个新的服务,其行为与FlipService不同。
@Service
public class NewFlipService {
public Foo getNewFoo() {
return new Foo("Shiny New Foo!", 100);
}
}
We will replace the old service’s getNewFoo() with the new version:
我们将用新版本替换旧服务的getNewFoo()。
@FlipBean(with = NewFlipService.class)
public Foo getNewFoo() {
return new Foo("New Foo!", 99);
}
Flips will direct calls to getNewThing() to NewFlipService. @FlipBean is another toggle that is most useful when combined with others. Let’s look at that now.
Flips将引导对getNewThing()的调用到NewFlipService。@FlipBean是另一个切换器,它与其他的切换器结合在一起时最有用。我们现在来看看这个。
7. Combining Toggles
7.组合切换器
We combine toggles by specifying more than one. Flips evaluates these in sequence, with implicit “AND” logic. Therefore all of them must be true to toggle the feature on.
我们通过指定一个以上的切换器来组合切换器。Flips用隐含的 “AND “逻辑依次评估它们。因此,所有这些都必须是真实的,才能开启该功能。
Let’s combine two of our previous examples:
让我们结合之前的两个例子。
@FlipBean(
with = NewFlipService.class)
@FlipOnEnvironmentProperty(
property = "feature.foo.by.id",
expectedValue = "Y")
public Foo getNewFoo() {
return new Foo("New Foo!", 99);
}
We’ve made use of the new service configurable.
我们已经使用了新的服务可配置。
8. Conclusion
8.结论
In this brief guide, we created a simple Spring Boot service and toggled APIs on and off using Flips annotations. We saw how features are toggled using configuration information and date/time, and also how features can be toggled by swapping beans at runtime.
在这个简短的指南中,我们创建了一个简单的Spring Boot服务,并使用Flips注解来切换API的开与关。我们看到了如何使用配置信息和日期/时间来切换功能,以及如何通过在运行时交换Bean来切换功能。
Code samples, as always, can be found over on GitHub.
像往常一样,可以在GitHub上找到代码样本。