在Spring Boot中使用Http Invoker

在Spring 中使用Http Invoker在官方文档中已经描述的很清楚了,那么,在Spring Boot中怎么使用呢?

首先我们定义一个接口:

public interface ITestService {
	String test(byte[] hello);
}

Server

在Server中,我们要一个对外提供服务的url,平时我们都是使用@Controller和@RequestMapping这两个注解实现对外提供服务,其实这里面Spring MVC做了很多动作,才让我们这么简单的把服务对外提供。

首先我们提供上述接口的实现类:

@Service
public class TestServiceImpl implements ITestService {

	@Override
	public String test(byte[] world) {
		return "测试成功!!!!!!" + new String(world, StandardCharsets.UTF_8);
	}
}

在Spring Boot中,我们只需要这样配置即可得到一个对外提供服务的url:

@Configuration
public class ServerConfiguration {

	@Bean("/testService")
	public HttpInvokerServiceExporter testService(ITestService testService) {
		HttpInvokerServiceExporter httpInvokerServiceExporter = new HttpInvokerServiceExporter();
		httpInvokerServiceExporter.setService(testService);
		httpInvokerServiceExporter.setServiceInterface(ITestService.class);
		return httpInvokerServiceExporter;
	}
}

很多人估计注意到了Bean的名字,为啥是“/”开头的?其实,在我们的Spring MVC中有一个很少用到的类:

org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping

它的作用就是把Spring MVC上下文中以“/”开头的Bean进行对外提供服务(注:根据配置可以把祖先上下文中“/”开头的Bean进行对外提供服务,默认情况下Spring Boot只有一个上下文,有兴趣的小伙伴可以自行研究下)。

按照上述配置,服务路径就是Bean的名称(即:http://IP:PORT/【上下文】/testService)。

Client

在客户端中我们只需要调用Server端中这个接口的实现就好了。那么我们怎么调用到呢?代码如下:

@Configuration
public class ClientConfiguration {

	@Value("${test.service.url}")
	private String testServiceUrl;

	@Bean
	public HttpInvokerProxyFactoryBean testService() {
		HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
		httpInvokerProxyFactoryBean.setServiceUrl(testServiceUrl);
		httpInvokerProxyFactoryBean.setServiceInterface(ITestService.class);
		return httpInvokerProxyFactoryBean;
	}
}

其实它就是一个远程服务的代理类。当你调用它的时候,它会去指定远程地址进行调用对应实现。

来我们测试一下

@Controller
public class TestController {

	@Autowired
	private ITestService testService;

	@ResponseBody
	@RequestMapping("test")
	public String test() {
		return testService.test("不知道在做啥!!".getBytes(StandardCharsets.UTF_8));
	}
}

请求结果:

测试完成!

详细代码可参考本人码云:https://gitee.com/Big_Xin/spring-learn/tree/master/spring-http-invoker/spring-http-invoker-demo

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值