簡體   English   中英

REST API Autowire自動對服務進行遠程或本地實施

[英]REST API Autowire remote or local implementation of a service automatically

我有一個在Spring Boot上構建的REST API,該API包含2個單獨的Web服務。 我不知道這兩個Web服務是否將托管在同一台計算機上,因此我想對所有服務進行遠程和本地實現。 下面的例子:

本地服務實施:

public class LocalExampleService implements ExampleService{

   public Item getItem(long id){
      //Get item using implementation from another local project
   }
}

遠程服務實現:

public class RemoteExampleService implements ExampleService{

   @Value("${serviceURL}")
   private String serviceURL;

   public Item getItem(long id){
      //Get item calling remote service
   }
}

控制器:

public class MyController{
    @Autowired
    private ExampleService exampleService;
}

Web服務有許多具有本地和遠程實現的服務,我想讓Spring知道應該為所有服務選擇哪種類型的實現。

我一直在考慮將url放入屬性文件中,並且在初始化過程中,該應用程序將檢查屬性是否包含url,然后適當地自動裝配服務。 但是隨后,我將不得不為每個服務自動裝配編寫邏輯。

自動為正確的服務實現自動接線的最佳選擇是什么?

您可以使用Spring配置文件來控制應通過spring屬性使用哪個版本的實現。

在春季屬性中,添加以下條目

spring.profiles.active=NAME_OF_ACTIVE_PROFILE

每個服務實現都需要配置文件注釋。 這就是您的服務實現的樣子:

@Component
@Profile("local")
public class LocalExampleService implements ExampleService{}

@Component
@Profile("remote")
public class RemoteExampleService implements ExampleService{}

如果您的項目需要使用服務的本地實現,則在屬性而不是NAME_OF_ACTIVE_PROFILE插入本地(否則為遠程)。

對於全自動布線,您需要添加在啟動時運行的方法,該方法檢查本地實現類是否存在,然后正確設置配置文件。 為此,您需要在spring boot main方法中修改代碼:

public static void main(String[] args){
    String profile = checkCurrentProfile(); //Method that decides which profile should be used
    System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, profile);
    SpringApplication.run(MyApplication.class, args);
}

如果選擇此方法,則不需要在屬性文件中先前輸入。

我試圖實現這樣的東西https://github.com/StanislavLapitsky/SpringSOAProxy

這個想法是檢查是否在本地找不到spring bean,然后自動創建一個代理,該代理在內部使用RestTemplate來遠程調用同一服務。

您需要定義合同-服務接口以及DTO,並定義URL解析器以指定每個服務應使用哪個URL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM