在MicroService开发中经常会遇到一个问题,自己的服务需要调用其它小组的服务,但是其他小组的服务还没有完成。为了不耽误进度,我们就需要先实现一个Mock的服务,最后再切换到真正的外部服务上去。同时,一旦外部服务出现问题,为了不阻塞本地开发,我们需要很方便的切换到Mock服务上去。通过修改配置文件里面的内容,可以实现不修改代码来切换不同的服务。
通用服务接口:
public interface OrderAtpChecker { /** * @param order order to be checked by ATP * @param tenant tenant id for client * @return a map whose key is the order line id and value is the validity of its apt check result */ MapatpCheck(Order order, String tenant); String getType();}
不同的服务实现:
public class MockOrderAtpChecker implements OrderAtpChecker { @Override public MapatpCheck(final Order order, final String tenant) { if (null == order) { throw new IllegalArgumentException("Can't atp check a null order."); } return order.getOrderLines().parallelStream() .collect(toMap(OrderLine::getId, o -> o.getQuantity() < 100)); } @Override public String getType() { return "Mock"; }}
public class OrderAtpChecker implements OrderAtpChecker { @Override public MapatpCheck(final Order order, final String tenant) { ............ } @Override public String getType() { return "Inventory"; }}
Service Factory的实现:
@Servicepublic class InventoryServiceFactory { @Autowired private Listservices; private static final Map myServiceCache = new HashMap<>(); @PostConstruct public void initMyServiceCache() { for (final OrderAtpChecker service : this.services) { myServiceCache.put(service.getType(), service); } } public static OrderAtpChecker getService(final String type) { final OrderAtpChecker service = myServiceCache.get(type); if (service == null) throw new RuntimeException("Unknown service type: " + type); return service; }}
具体调用服务的地方:
@Value("${inventory_service}")private String serviceType;private OrderAtpChecker orderAtpChecker;this.orderAtpChecker = InventoryServiceFactory.getService(this.serviceType);