2、springcloud微服务:基于Feign的服务调用

摘要:Feign是一个声明式、模板化的HTTP客户端调用组件,它可以像调用本地方法一样调用远程服务

创建一个新的服务:microservice-provider-user,在microservice-provider-user中使用Feign调用microservice-provider-org发布的服务/org/query/{id}。

1、以microservice-provider-org作为模板创建一个springboot服务:microservice-provider-user,在maven配置中增加依赖:

<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-feign</artifactId>  
</dependency> 

2、修改application.yml的服务名和端口号:

server:  
  port: 9002  
spring:  
  application:  
    name: user-service #服务名,将注册到eureka注册中心  
eureka:  
  instance:  
    statusPageUrlPath: ${management.context-path}/info  
    healthCheckUrlPath: ${management.context-path}/health  
  client:  
    serviceUrl:  
      defaultZone: http://localhost:8761/eureka/ #注册地址,eureka服务地址  

3、启动类增加Feign注解:@EnableFeignClients。

4、使用Feign调用microservice-provider-org发布的服务:

package com.netsframe.user.service;  
  
import org.springframework.cloud.netflix.feign.FeignClient;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@FeignClient("org-service")  
public interface UserService {  
    @RequestMapping("/org/query/{id}")  
    public String queryOrg(@PathVariable("id") String id);  
}  
@FeignClient:发现microservice-provider-org发布到注册中的服务。

 

5、在controller调用UserService:

package com.netsframe.user.rest;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
import com.netsframe.user.service.UserService;  
  
@RestController()  
public class UserController {  
    @Autowired  
    UserService userService;  
  
    @RequestMapping("/user/query/{id}")  
    public String query(@PathVariable("id") String id) {  
        String org = userService.queryOrg(id);  
        return "小陈所属组织:" + org;  
    }  
}  

6、依次启动microservice-register-eureka、microservice-provider-org、microservice-provider-user,访问http://localhost:8761/,显示如下界面:


从上图看出,新的服务USER-SERVICE已经发布到注册中心了,访问user-service中的请求:http://localhost:9002/user/query/1,返回:


从上面返回结果看,在microservice-provider-user中通过feign调用microservice-provider-org发布的服务成功。

至此,本文介绍的通过Feign调用服务结束。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值