背景:微服务开发应该按照功能模块来划分各个微服务,各个微服务为了实现高内聚低耦合,应该实现分库分表,即一个微服务对应一个数据库schema。 但是我们的业务需求可能需要各个微服务之间的拼接,我的建议是编写编排层,不要在底层join其它schema的表

 

编排层:根据业务需求调用微服务底层的api,组装前端所需要的数据

 

项目中的应用:

1.在编排层创建实体类(常量的值应该与服务在注册中心中的名字一致)

public class FeignClientConstants {
  public static final String EXTERNAL_USER_SERVICE = "external-user";
  public static final String USER_SERVICE = "user";
  public static final String DEVELOPMENT_OBJECTIVE_SERVICE = "development";
  public static final String FEEDBACK_SERVICE = "feedback-service";

  private FeignClientConstants() {}
}

 

2.Decoder配置

import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import org.springframework.cloud.netflix.feign.FeignClientsConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(FeignClientsConfiguration.class)
public class DefaultFeignClientConfiguration {
  @Bean
  ErrorDecoder errorDecoder(Decoder decoder) {
    return new DefaultFeignErrorDecoder(decoder);
  }
}
 

3.对底层api进行调用

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.capgemini.capgenie.mobile.config.FeignClientConstants;
import com.capgemini.capgenie.mobile.domain.common.PageResult;
import com.capgemini.capgenie.mobile.domain.feedback.FeedbackVo;

@FeignClient(name = FeignClientConstants.FEEDBACK_SERVICE, decode404 = true)
public interface FeedbackClient {
  
  @PutMapping(value = "/api/v1/user/{id}/feedbacks")
  String giveFeedback(
      @PathVariable(value = "id") String userId, 
      @RequestParam(value = "recipientId") String recipientId,
      @RequestParam(value = "description") String description);
  
}
 

4.编排层一般会有controller和service两层

controller调用各个微服务的service对需要的信息进行组装,在各个service中调用各个微服务的client中所需要的api

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐