如何将我的新策略注册到 FF4j 中?
让我们提醒一下策略代码
public class MarketFlippingStrategy extends AbstractFlipStrategy {
private final Set<String> setOfGrantedMarket = new HashSet<String>();
@Override
public void init(String featureName, Map<String, String> initValue) {
super.init(featureName, initValue);
assertRequiredParameter("grantedMarket");
String[] arrayOfRegions = initValue.get("grantedMarket").split(",");
setOfGrantedRegions.addAll(Arrays.asList(arrayOfRegions));
}
@Override
public boolean evaluate(String fName, FeatureStore fStore, FlippingExecutionContext ctx) {
return setOfGrantedRegions.contains(ctx.getString("market", true));
}
}
FlipStrategy
应该在特性的定义中注册legacy-api
:
- 您可以使用 Web 控制台手动执行此操作(功能 > 编辑功能 > 选择字段策略并编辑类和参数 (param1=value1)。
- 您可以在文件中执行此操作并使用控制台 ff4j now support
xml
或.yaml
properties
使用以下定义,该功能将仅对授权市场启用:
<?xml version="1.0" encoding="UTF-8" ?>
<features>
<feature uid="legacy-api" enable="true" >
<flipstrategy class="org.ff4j.sample.strategy.MarketFlippingStrategy" >
<param name="grantedMarket">country1-brand1,country1-brand2</param>
</flipstrategy>
</feature>
</features>
如何根据家庭控制器品牌/国家输入在 API 之间动态切换?
“诀窍”是将夫妇品牌/国家作为单个变量传递market
,这将帮助您理解它是如何工作的。FlippingExecutionContext
@RestController
@RequestMapping("/{brand}/{country}")
public class HomeController {
private final ApiService apiService;
public HomeController(@Qualifier("new-api") ApiService apiService) {
this.apiService = apiService;
}
@GetMapping("/hey")
public String hey(@PathVariable("brand") String brand,
@PathVariable("country") String country) {
FlippingExecutionContext executionContext = new FlippingExecutionContext();
executionContext.putString("market", brand + "-" + country);
return apiService.whichApi(executionContext);
}
}
interface ApiService {
@Flip(name = "legacy-api",
alterBean = "legacy-api",
flippingStrategy = MarketFlippingStrategy.class,
contextLocation = ContextLocation.PARAMETER)
String whichApi(FlippingExecutionContext context);
}
@Component("new-api")
class NewApiApiService implements ApiService {
@Override
public String whichApi(FlippingExecutionContext context) {
return "NEW_API";
}
}
@Component("legacy-api")
class LegacyApiApiService implements ApiService {
@Override
public String whichApi(FlippingExecutionContext context) {
return "LEGACY_API";
}
}