Situation: A microservices architecture with:
enabled
status associated with it. It is unlikely that more attributes belonging to Option will be added in future which have to be directly tied to it.enum OptionType {
TYPE_A,
TYPE_B,
TYPE_C;
}
enum Option {
TYPE_A_X1(TYPE_A),
TYPE_A_X2(TYPE_A),
TYPE_B_Z1(TYPE_B, false),
TYPE_B_Z2(TYPE_B);
TYPE_C_U1(TYPE_C);
TYPE_C_U2(TYPE_C);
TYPE_C_U3(TYPE_C);
private final OptionType type;
private final boolean enabled;
Option(OptionType type){
this.type = type;
this.enabled = true;
}
Option(OptionType type, boolean enabled){
this.type = type;
this.enabled = enabled;
}
}
{
"typeA": "TYPE_A_X1",
"typeB": "TYPE_B_Z2",
"typeC": [ "TYPE_C_U1", "TYPE_C_U2"]
// more filter settings
}
Different approaches of storing and sharing this Option data between microservices as I see it:
options-service stores Option data in its own database. If I read my data from database into my Hibernate entities Option is only a String
everywhere from there on.
String
s)Option data only lives in source code in an enum
as e.g. modelled above and is shared between different services via a lib.
There is also the possibility of a mixed database and enum solution which comes with the big drawback that one has to maintain both sources of truth.
What is the best way to store and share the Option data between microservices? What is best practice?
Enums force you to use multiple switch case One primary reason ENUMs are considered code smells is that they tempt you to sprinkle switch statements throughout your code.
While enums are very helpful in most programming languages, they can become a nightmare in inter-service communication. If you use an enum in your microservice endpoints, it becomes part of the API specification. Changing them on one side will result in problems of serialization/deserialization on the other side. So you should only use enums in your API if
In these cases, you may create a shared lib between your services.
If this does not apply, make your life easier and consider most enum-like data (e.g. currency codes, country codes) as simple string values that are subject to change. If you want to have a central management for these values, why don't create a microservice for it that acts as a master? That's what microservice architectures are made for. Offer some endpoints that other services can query from time to time. You don't even need a persistence layer for that.
Another option : Use the first option, but with a specialised class.
Option
instance, you need a service that has cached the list of allowed Option
s.Example code:
import com.fasterxml.jackson.annotation.JsonValue;
public class Option {
@JsonValue
private String value;
Option(String value) {
this.value = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With