SpringCloud中Service类注入同服务下(@Feign)api接口不走http的解决方案

在spring cloud项目中经常会有一个服务需要依赖另外一个服务的api包,从而使用其接口实现。在我们使用@Feign的时候,其实是用本质上采用的是http调用摸个服务下的其接口实现,那么http调用的话,就会多产生一个线程,如图测试,

2018-04-22 00:37:26.517  INFO 24548 --- [nio-9999-exec-4] c.d.c.eureka.discovery.UserServiceImpl   : http-nio-9999-exec-4
2018-04-22 00:37:26.523  INFO 24548 --- [nio-9999-exec-5] c.d.c.e.discovery.MessageServiceImpl     : http-nio-9999-exec-5

我们习惯是用api中的接口去注入到我们的service类中。 当在同一个服务里面一个接口被其他service类autowird注入时候,以为是@Feign,岂不是通过http调用,多绕了很多弯路,自己service没有必要这要,当然你可以注入其接口实现,如图

    @Autowired
    private MessageServiceImpl messageService;

但是如果是这个样子,就不方便以后服务拆分,所以可以采取@Resource(name=”“),以为这个是根据名称找到spring中bean的,如这样使用

    @RestController("MessageService")
    class MessageServiceImpl implements MessageService

而其他同服务下service类采用如下注入

    @Resource(name = "messageService")
    private MessageService messageService;

效果测试

2018-04-22 00:31:49.511  INFO 13688 --- [nio-9999-exec-5] c.d.c.eureka.discovery.UserServiceImpl   : http-nio-9999-exec-5
2018-04-22 00:31:49.511  INFO 13688 --- [nio-9999-exec-5] c.d.c.e.discovery.MessageServiceImpl     : http-nio-9999-exec-5

猜你喜欢

转载自blog.csdn.net/zyt807/article/details/80035389