开发原则:一个微服务最好对应一个数据库schema,如果需要参数需要其它schema表中参数,调用对应schema其对应微服务所暴露出来的api。(*****)
下面将具体介绍怎么在一个微服务中调用另一个微服务(注册中心使用的是eurake)
1.先创建一个外部微服务的包,在包下创建对应微服务的Clients和Client对象,注意不要直接使用client对象,要用clients对象get。
下面是实例代码:(因为项目中用到了Oauth2,所以clients会多出一点)
@Component
@Import(FeignClientsConfiguration.class)
public class xxxClients {
private xxxClient userClient;
private xxxClient client;
@Autowired
public xxxClients(
Decoder decoder, Encoder encoder, Client client, Contract contract,
LoadBalancedResourceDetails loadBalancedResourceDetails,
RequestInterceptor oauth2RequestInterceptor,
RequestInterceptor userFeignClientInterceptor
) {
this.client = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(oauth2RequestInterceptor)
.target(xxxClient.class, "http://xxx");
this.userClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(userFeignClientInterceptor)
.target(xxxClient.class, "http://xxx");//这里填写微服务在eurake中注册的名称
}
public xxxClient getUserClient() {
return userClient;
}
public xxxClient getClient() {
return client;
}
}
@FeignClient(name="被调用微服务的名称");下面是具体的api及访问路径
2.LoadBalancedResourceDetails(Clients中引入的一个类,没有加导包) :
@ConditionalOnMissingBean
public class LoadBalancedResourceDetails extends ClientCredentialsResourceDetails {3.根据业务调用其它微服务的api