stackuser
stackuser

Reputation: 4191

Database driven feature toggle

I would want to enable my new feature based on a database value . If the database value is set for the feature , the new code should be enabled. Else it should toggle and flow to the old code. is there a way to accomplish this in Java/Spring ? I do not want to hit the database frequently.I am thinking of one call at the start of the request . Are there any examples to this ? If so please let me know. Thanks

Upvotes: 1

Views: 1515

Answers (1)

Romas Augustinavičius
Romas Augustinavičius

Reputation: 443

Create Feature class implementation:

public enum CustomFeatures implements Feature {
    @Label("Activates customFeature")
    MY_CUSTOM_FEATURE;

    public boolean isActive() {
        return FeatureContext.getFeatureManager().isActive(this);
    }
}

Create feature provider:

@Bean
public FeatureProvider featureProvider() {
    return new EnumBasedFeatureProvider(CustomFeatures.class);
}

Create entity and repository:

@Entity
public class Feature {

    private String name;
    private Boolean active;
    // getters-setters
}

Create @Component which will query database and sets new feature sate

@Component
public class FeatureToggler {

   private final FeatureRepository featureRepository;
   private final FeatureManager featureManager;

   private FeatureToggler(FeatureRepository featureRepository, FeatureManager featureManager) {
      this.featureRepository = featureRepository;
      this.featureManager = featureManager;
   }

   @Schedule(fixedRate=60000)
   public void refreshFeatureToggles() {
        featureManager.setFeatureState(new FeatureState(CustomFeatures.MY_CUSTOM_FEATURE, featureRepository.findByName().isActive);
   }


}

Now you could use check if feature enabled like this:

if(CustomFeatures.MY_CUSTOM_FEATURE.isActive()) {
}

Or use Spring aspect..

Upvotes: 2

Related Questions