服务A调用服务B的另一种方式
服务A调用服务B:
01、采用HttpClient的方式
02、采用微服务的方式(feign)
03、HttpInvokerProxyFactoryBean(代理对象的方式)
说一下第三种,之前没有接触过第三种方式:
有两种方式一种老的xml的方式和新的集成在springboot中的方式
我自己使用的springboot的方式,话不多说,开始代码
服务A对外提供服务:
声明service和声明service的实现:这个和普通的没有区别,除此之外需要新增一个配置类(用来对外提供服务)
package com.example.demo.config;
import com.example.demo.service.testService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
@Configuration
public class ServerConfiguration {
@Bean("/testService")
public HttpInvokerServiceExporter testService(testService testService) {
HttpInvokerServiceExporter httpInvokerServiceExporter = new HttpInvokerServiceExporter();
httpInvokerServiceExporter.setService(testService);
httpInvokerServiceExporter.setServiceInterface(testService.class);
return httpInvokerServiceExporter;
}
}
路径的含义用来对外提供服务,方便客户端调用
服务B访问A提供的服务:
配置类信息
package com.first.config;
import com.first.service.testService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
@Configuration
public class clientService {
@Value("${test.service.url}")
private String testServiceUrl;
@Bean
public HttpInvokerProxyFactoryBean testService() {
HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
httpInvokerProxyFactoryBean.setServiceUrl(testServiceUrl);
httpInvokerProxyFactoryBean.setServiceInterface(testService.class);
return httpInvokerProxyFactoryBean;
}
}
url的地址是A服务的地址:例如(test.service.url=http://127.0.0.1:8080/testService)
在B服务中的调用就简单多了直接注入testService对象就可以了(这个和feigin有点类似,需要在B的服务中对接口重新写一遍,但是具体的实现不用做,会自动跳转到A服务进行处理)
@Autowired
private com.first.service.testService testService;
好了接下来就是注入对象直接访问了。
有一个注意事项需要提一下,如果B服务访问A服务有处理结果的返回,需要对返回结果的实体进行序列化,序列化ID要和A的Bean保持一致,路径也需要保持一致,不然会报错。java.lang.ClassNotFoundException