天天看点

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

RestTemplate 简介

RestTemplate是由Spring提供的一个HTTP请求工具。RestTemplate是从Spring3.0开始支持的一个HTTP请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST请求、PUT请求、DELETE请求以及一些通用的请求执行方法exchange以及execute。RestTemplate继承自InterceptingHttpAccessor并且实现了RestOperations 接口,其中RestOperations接口定义了基本的 ​

​restful​

​操作,这些操作在RestTemplate中都得到了实现。

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

创建第一个Spring Boot项目作为注册中心。

​pom.xml​

​如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.kaven</groupId>
    <artifactId>eureka</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>eureka</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR2</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>      

​application.yml​

​如下:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: false
  server:
    enable-self-preservation: false

spring:
  application:
    name: eureka

server:
  port: 8761      

启动类:

package com.kaven.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }
}      

注解​

​@EnableEurekaServer​

​不要忘记加上。

创建第二个Spring Boot项目作为第一个微服务。

​​

​pom.xml​

​如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.kaven</groupId>
    <artifactId>server</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>server</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>      

​application.yml​

​如下:

spring:
  application:
    name: server

server:
  port: 8001

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/      

启动类:

package com.kaven.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }
}      

注解​

​@EnableDiscoveryClient​

​不要忘记加上。

再写一个接口(用于被其他微服务请求):

package com.kaven.server.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageServerController {

    @GetMapping("/getMessage")
    public String getMessage(){
        return "hello , Jack";
    }
}      

创建第三个Spring Boot项目作为第二个微服务。

​​

​pom.xml​

​如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.kaven</groupId>
    <artifactId>client</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>client</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>      

​application.yml​

​如下:

spring:
  application:
    name: client

server:
  port: 8002

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/      

启动类:

package com.kaven.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }
}      

注解​

​@EnableDiscoveryClient​

​不要忘记加上。

再写一个接口用来请求第一个微服务的接口:

package com.kaven.client.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MessageController {

    @GetMapping("/getMessage")
    public String getMessage(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://127.0.0.1:8001/getMessage";
        String message = restTemplate.getForObject(url , String.class);
        return "get: "+message;
    }
}      

访问​

​http://localhost:8761/​

​,可以得到如下图所示的界面:

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

可以发现两个微服务已经注册上去了,发出警告的原因是因为注册中心关闭了自我保护模式。访问​

​http://localhost:8001/getMessage​

​,即第一个微服务的接口,可以得到如下图所示的界面。

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

再来访问​

​http://localhost:8002/getMessage​

​,即第二个微服务的接口,可以得到如下图所示的界面。

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

该接口会通过RestTemplate来请求第一个微服务的接口,以便获取数据。

这就是使用RestTemplate实现微服务之间相互请求的第一种方式,这种方式把微服务的接口​

​url​

​写死了,代码不优雅,并且不利于维护。

下面来介绍第二种方式。

修改第二个微服务的接口:

package com.kaven.client.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MessageController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/getMessage")
    public String getMessage(){
        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose("server");
        String url = String.format("http://%s:%s//getMessage" , serviceInstance.getHost() , serviceInstance.getPort());
        String message = restTemplate.getForObject(url , String.class);
        return "get: "+message;
    }
}      

这里使用到了​

​LoadBalancerClient​

​​,这种方式是不是比上一种方式优雅许多,不用写死​

​ip​

​​和​

​port​

​,只要写接口即可。

再来访问​

​http://localhost:8002/getMessage​

​,可以得到如下图所示的界面,所以这种方式也是成功的。

Spring Cloud 之使用RestTemplate实现微服务之间相互请求的三种方式

但第二种方式代码量稍多,并不简洁,接下来介绍第三种方式。

第三种方式首先需要加一个配置类:

package com.kaven.client.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}      

注解​

​@LoadBalanced​

​是关键。

再来修改第二个微服务的接口:

package com.kaven.client.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MessageController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getMessage")
    public String getMessage(){

        String message = restTemplate.getForObject("http://server/getMessage" , String.class);
        return "get: "+message;
    }
}      

除了配置类,接口主要代码就一行,是不是很简洁,​

​server​

​​是第一个微服务的名称,这种方式直接使用服务名称即可,可以知道这肯定是注解​

​@LoadBalanced​

​的功劳,其实这种方式和第二种方式是一样的,只是实现方式不一样。

再来访问​

​http://localhost:8002/getMessage​

​,可以得到如下图所示的界面,所以第三种方式也是成功的。