Spring Cloud【Finchley】-06服务消费者整合Feign

简介: Spring Cloud【Finchley】-06服务消费者整合Feign

20190806093230928.jpg


概述


回想下我们在使用Eureka 和 Ribbon的时候是怎么调用注册在Eureka Server上的微服务的地址呢?

20181209213253513.png


可以看到其实是通过拼接的方式,当然了我们上面的这个例子只有一个参数 id,看起来没有这麻烦。


设想下如果有多个参数呢?

假设URL如下

http://localhost:8080/search?name=小工匠&age=20&username=artisan


那我们用RestTemplate如何调用对方的微服务呢? 可以采用如下方式

  @GetMapping("/searchUser")
  public User searchUser(String name ,String age ,String username) {
    Map<String, Object> paraMap = new HashMap<String ,Object>() {
      {
        put("name",name);
        put("age",age);
        put("username",username);
      }  
    };
   return  this.restTemplate.getForObject("http://microservice-provider-user/search?name={name}&age={age}&username={username}", User.class, paraMap);
  }


是不是已经很麻烦了?


Spring Cloud为我们整合了Fegin解决上述苦恼。


Feign官方文档: https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#_spring_cloud_openfeign


Feign是Netflix开发的声明模板化的HTTP客户端。 在Spring Cloud中使用Feign,只需要创建一个接口,并在接口上添加一些注解即可。 Spring Cloud对Feign进行了增强,使Feign支持了SpringMVC的总结,并整合了Ribbon和Eureka。


实例

新建工程

在父工程上右键,新建Maven Module ,如下


20181209222253911.png

下面根据官方文档操作即可


20181209222608915.png


增加maven依赖

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


创建一个Feign接口,并添加@FeignClient注解

package com.artisan.micorservice.feignclient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.artisan.micorservice.model.User;
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
  public User findById(@PathVariable Long id);
}


FeignClient中的microservice-provider-user是要调用的微服务的名称,用于创建Ribbon负载均衡器。


因为我们这里使用了Eureka,所以Ribbon会把microservice-provider-user解析成Eureka Server中注册的服务。


另外,也可以通过url属性指定请求的URL ,比如 @FeignClient("microservice-provider-user", url="http://localhost:8900/")


修改Controller层,将RestTemplate改为调用Feign接口

package com.artisan.micorservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.artisan.micorservice.feignclient.UserFeignClient;
import com.artisan.micorservice.model.User;
@RestController
public class MovieController {
 @Autowired
 private UserFeignClient userClient;
  @GetMapping("/movie/{id}")
  public User findById(@PathVariable Long id) {
    return userClient.findById(id);
  }
}


启动类增加@EnableFeiginClients注解

package com.artisan.micorservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class MicorserviceConsumerFeginApplication {
  public static void main(String[] args) {
    SpringApplication.run(MicorserviceConsumerFeginApplication.class, args);
  }
}



测试

  1. 启动eureka server微服务
  2. 启动2个 provider-user微服务
  3. 启动该微服务


20181209225838562.png


2次请求http://localhost:7901/movie/1 ,观察 provider-user微服务的日志打印情况。

8900端口

20181209230212894.png

8901端口

2018120923015076.png



通过日志可以看到不仅实现了声明式的REST API调用,同时也实现了客户端的负载均衡。


源码

https://github.com/yangshangwei/SpringCloudMaster

相关文章
|
7月前
|
负载均衡 算法 Java
【SpringCloud(4)】OpenFeign客户端:OpenFeign服务绑定;调用服务接口;Feign和OpenFeign
Feign是一个WebService客户端。使用Feign能让编写WebService客户端更加简单。 它的使用方法是定义一个服务接口然后再上面添加注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,十七支持了SpringMVC标准注解和HttpMessageConverters。 Feign可用于Eureka和Ribbon组合使用以支持负载均衡
933 139
|
人工智能 Java Serverless
【MCP教程系列】搭建基于 Spring AI 的 SSE 模式 MCP 服务并自定义部署至阿里云百炼
本文详细介绍了如何基于Spring AI搭建支持SSE模式的MCP服务,并成功集成至阿里云百炼大模型平台。通过四个步骤实现从零到Agent的构建,包括项目创建、工具开发、服务测试与部署。文章还提供了具体代码示例和操作截图,帮助读者快速上手。最终,将自定义SSE MCP服务集成到百炼平台,完成智能体应用的创建与测试。适合希望了解SSE实时交互及大模型集成的开发者参考。
15113 60
|
10月前
|
Prometheus 监控 Cloud Native
Docker 部署 Prometheus 和 Grafana 监控 Spring Boot 服务
Docker 部署 Prometheus 和 Grafana 监控 Spring Boot 服务实现步骤
892 0
|
人工智能 自然语言处理 Java
对话即服务:Spring Boot整合MCP让你的CRUD系统秒变AI助手
本文介绍了如何通过Model Context Protocol (MCP) 协议将传统Spring Boot服务改造为支持AI交互的智能系统。MCP作为“万能适配器”,让AI以统一方式与多种服务和数据源交互,降低开发复杂度。文章以图书管理服务为例,详细说明了引入依赖、配置MCP服务器、改造服务方法(注解方式或函数Bean方式)及接口测试的全流程。最终实现用户通过自然语言查询数据库的功能,展示了MCP在简化AI集成、提升系统易用性方面的价值。未来,“对话即服务”有望成为主流开发范式。
9762 7
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
1072 7
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
423 6
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
340 5
|
缓存 监控 Java
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
371 5
|
10月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1374 0