首页 > 其他分享 >SpringCloud学习笔记二:服务间调用

SpringCloud学习笔记二:服务间调用

时间:2024-03-24 14:59:08浏览次数:27  
标签:调用 SpringCloud RestTemplate springframework eureka client 笔记 import org

微服务中,很多服务系统都在独立的进程中运行,通过各个服务系统之间的协作来实现一个大项目的所有业务功能。服务系统间 使用多种跨进程的方式进行通信协作,而RESTful风格的网络请求是最为常见的交互方式之一。

spring cloud提供的方式:

1.RestTemplate
2.Feign

一、服务提供者创建

在上一篇文章中我们介绍了服务的注册与发现,在此基础上我们将之前创建的eureka-client作为服务消费方创建一个服务提供方。

1.按照上篇文章中创建eureka-client的方式创建eureka-provider

 其中application的配置如下

#指定启动端口号
server.port=5202

#设置服务注册中心的URL,用于client和server端交流
eureka.client.service-url.defaultZone=http://localhost:5200/eureka/

#指定服务名称
spring.application.name=eureka-provide


2.创建服务提供方的ProviderController
1.在包下创建controller.ProviderController,如下图:

2.写入被调用的提供方法
package shadowcoder.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
        @GetMapping("/hello")
        public String hello() {
            return "Hello from Eureka Provider!";
        }
}

二、RestTemplate方式调用

RestTemplate是Spring框架提供的一个工具类,主要用于简化访问RESTful服务的过程。它是从Spring3.0开始支持的一个HTTP请求工具,它封装了底层的HTTP请求细节,让我们可以以更加优雅和简洁的方式调用RESTful API。

1.启动类配置一个RestTemplate的Bean,并标记为@LoadBalanced,以便Spring Cloud能够为其添加负载均衡支持
package com.shadowcoder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaClientApplication.class, args);
	}
	@Bean
	@LoadBalanced // 使得RestTemplate具有负载均衡的能力
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

}
2.在eureka-client包下创建controller.ConsumerController,结构如图

3.在ConsumerController写入调用服务提供者的API:/call-hello1
package com.shadowcoder.controller;

import com.netflix.appinfo.InstanceInfo;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.discovery.EurekaClient;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    EurekaClient client;


    private final RestTemplate restTemplate;


    @Autowired
    public ConsumerController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @GetMapping("/call-hello")
    public String callHello() {
        //获取服务名为eureka-provide的服务实例
        List<InstanceInfo> instances = client.getInstancesByVipAddress("eureka-provide", false);
        InstanceInfo instanceInfo = instances.get(0);
        //打印调用的接口
        System.out.println("http://" + instanceInfo.getHostName() +":"+ instanceInfo.getPort() + "/hello");
        String url = "http://" + instanceInfo.getHostName() +":"+ instanceInfo.getPort() + "/hello";
        //服务提供者的API
        String response = restTemplate.getForObject(url, String.class);
        return "Response from Service Provider: " + response;
    }

}

(备注):通过打印的调用接口发现 实际调用的是eureka的主机名而不是spring.application.name的eureka-provider

4.测试调用接口:/call-hello1

访问localhost:5201/call-hello可以发现出现成功调用了eureka-provide的/hello方法

三、Feign方式调用

Feign是一个声明式的Web服务客户端,它使得编写HTTP客户端变得更简单。在Spring Cloud中,Feign可以很容易地与Eureka等服务发现机制集成,从而实现对微服务的调用。

1.在eureka-client中添加Feign依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.shadowcoder</groupId>
        <artifactId>SpringCloudTest</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>eureka-client</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

</project>
2.启动类上添加@EnableFeignClients注解来启用Feign客户端,代码如下
package com.shadowcoder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaClientApplication.class, args);
	}
	@Bean
	@LoadBalanced // 使得RestTemplate具有负载均衡的能力
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

}
3.包下新增一个接口service.ConsumerService

代码如下:

package com.shadowcoder.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(value = "eureka-provide")//value填写提供方的spring.application.name=eureka-provide
public interface ConsumerService {
    //提供方的调用API
    @GetMapping("/hello")
    String hello();
}
4.在ConsumerController注入ConsumerService以及写入调用服务提供者的API:/call-hello2
package com.shadowcoder.controller;

import com.netflix.appinfo.InstanceInfo;
import com.shadowcoder.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.discovery.EurekaClient;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    EurekaClient client;
    @Autowired
    private ConsumerService consumerService;
    private final RestTemplate restTemplate;


    @Autowired
    public ConsumerController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @GetMapping("/call-hello")
    public String callHello() {
        //获取服务名为eureka-provide的服务实例
        List<InstanceInfo> instances = client.getInstancesByVipAddress("eureka-provide", false);
        InstanceInfo instanceInfo = instances.get(0);
        //打印调用的接口
        System.out.println("http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/hello");
        String url = "http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/hello";
        //服务提供者的API
        String response = restTemplate.getForObject(url, String.class);
        return "Response from Service Provider: " + response;
    }


    @GetMapping("/call-hello2")
    public String callHello2() {
        return "Response from Service Provider2: " + consumerService.hello();
    }


}

5.测试调用接口:/call-hello2

访问localhost:5201/call-hello2可以发现出现成功调用了eureka-provide的/hello方法

备注(提示):

1.要在启动类中加入@EnableFeignClients注解,以便Spring Cloud能够扫描到@FeignClient注解并创建Feign客户端。
2.Feign主要通过接口调用,底层实现是HttpClient或OkHttp。在定义Feign接口时,需要加入对应的Rest接口,并设置接口的参数。如果接口参数是对象或Map,应使用@RequestBody注解;如果参数是字符串,应使用@RequestParam注解。

标签:调用,SpringCloud,RestTemplate,springframework,eureka,client,笔记,import,org
From: https://blog.csdn.net/RHeng/article/details/136982954

相关文章

  • Programming Abstractions in C阅读笔记:p338-p346
    《ProgrammingAbstractionsinC》学习第80天,p338-p346,总计9页。一、技术总结栈的实现包括入栈、出栈、判断栈是否为满,判断栈是否为空等。作者结合RPN计算器来实现,稍显无聊。/**File:rpncalc.c*---------------*Thisprogramsimulatesanelectroniccalculatorth......
  • JS AVL树(数据结构)- 笔记
    Code: /***AVL树*@class*/classAVLTree{/***@type{TreeNode}*/#root;/***@constructor*/constructor(){this.#root=null;}/***获取节点高度*@param{TreeNode}node*......
  • JavaWeb学习笔记——第三天
    Ajax概述Ajax全称AsynchronousJavaScriptAndXML,异步的JavaScript和XML。作用数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用的校验等等。同......
  • FFmpeg开发笔记(八)Linux交叉编译Android的FFmpeg库
    ​《FFmpeg开发实战:从零基础到短视频上线》一书的“12.1.2 交叉编译Android需要的so库”介绍了如何在Windows环境交叉编译Android所需FFmpeg的so库,接下来介绍如何在Linux环境交叉编译Android所需FFmpeg的so库。1、下载Linux版本的android-ndk-r21e登录Linux服务器(比如华为云的......
  • FFMpeg笔记(十二)升级FFmpeg6.1
      FFmpeg最新版已更新6.1,许多之前标记为deprecated的api被彻底删除了,同时也增加了好多新的特性和功能。FFmpeg团队持续优化代码,新版本往往具有更高的编码和解码效率,因此及时更新FFmpeg版本,有利于提升应用的处理速度和资源利用率。本文记录项目中FFmpeg更新至6.1版本过程中遇到......
  • 高等代数笔记:矩阵运算
    目录矩阵运算和(加法)数乘负矩阵运算法则矩阵乘法特殊矩阵对角矩阵基本矩阵上(下)三角矩阵初等矩阵对称矩阵斜对称矩阵矩阵乘积的秩与行列式矩阵乘积的秩矩阵乘积对应行列式矩阵运算2个矩阵相等:行数、列数相等,且所有位置对应元素相等.即:A的(i,j)元=B(i,j)元矩阵有三种运算:......
  • SpringCloud之Nacos
    SpringCloud之Nacosnacos作为注册中心服务提供者添加依赖<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>配置Nacos注册中心spring:application......
  • 替代 Evernote!离线优先、数据安全的个人笔记 | 开源日报 No.205
    laurent22/joplinStars:40.4kLicense:NOASSERTIONjoplin是一个安全的笔记和待办事项应用程序,具有Windows、macOS、Linux、Android和iOS的同步功能。可以处理大量笔记,可以组织成笔记本笔记可搜索,并且支持标签和Markdown格式支持从Evernote导入格式化内容和......
  • C# 执行外部程序方法_可调用
    //新建一个cs文件,放在你的项目内,可以调用这个方法。usingSystem;usingSystem.Diagnostics;//调用程序namespaceShutdown{classProces{publicstaticvoidProgress(stringProce,stringParameter,uintX){Processp=......
  • 高架学习笔记之需求工程
    目录一、什么是软件需求二、需求工程2.1. 需求获取2.2.需求分析2.3. 形成需求规格2.4. 需求确认2.5.需求管理2.5.1. 变更控制2.5.2. 版本控制2.5.3. 需求跟踪2.5.4. 需求状态跟踪一、什么是软件需求    软件需求目前没有统一的定义,一般是指用户为......