【问题标题】:REST API Autowire remote or local implementation of a service automaticallyREST API 自动连接远程或本地服务的实现
【发布时间】:2018-01-27 03:51:53
【问题描述】:

我有一个基于 Spring Boot 构建的 REST 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,然后适当地自动连接服务。但是我必须为每个服务自动装配编写逻辑。

自动装配正确的服务实现的最佳选择是什么?

【问题讨论】:

  • 你能解释更多吗?您的意思是应用程序的一个实例一次只需要一个或另一个?或者你需要在运行时决定你需要哪个?
  • @Brian 我有两个独立的网络服务。如果两个 Web 服务都托管在同一台机器上,那么 Spring 应该自动连接服务的本地实现(直接调用其他服务以避免冗余延迟)否则远程实现(通过 REST 调用其他服务)。

标签: java spring rest spring-boot microservices


【解决方案1】:

您可以使用 Spring 配置文件通过 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);
}

如果您选择这种方法,那么您不需要在属性文件中输入之前的条目。

【讨论】:

    【解决方案2】:

    我尝试实现类似https://github.com/StanislavLapitsky/SpringSOAProxy 的东西

    这个想法是检查是否在本地找不到 spring bean,然后自动创建一个代理,它在内部使用 RestTemplate 来远程调用相同的服务。

    您需要定义契约 - 服务接口加上 DTO 并定义 URL 解析器以指定每个服务应使用哪个 URL。

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 2019-04-19
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多