SpringCloud Part 3: Service Provision and Feign Call

Posted Jun 28, 20208 min read

In the previous article, we introduced the construction of the registration center, including the cluster environment to scare the registration center. This article introduces how to use the registration center to create a service provider and use a simple client to call the service provided by the server. service.

This article requires three roles, namely the service provider, the service consumer, and the protagonist of the previous article-the registration center Eureka(you can use the stand-alone version, the examples in this article will also be used Standalone version of Eureka).

The overall process is:

  1. Start the registration center Eureka first
  2. The provider who started the service will provide the service and register the service on the registration center Eureka
  3. Consumers who start the service, find the service in the registration center and complete the consumption

1. Service provider

1. 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 http://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.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springcloud</groupId>
    <artifactId>producer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>producer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</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>

2. Configuration file application.yml

server:
  port:8080
spring:
  application:
    name:spring-cloud-producer
eureka:
  client:
    service-url:
      defaultZone:http://localhost:8761/eureka/

3. Start class ProducerApplication.java

Add @EnableEurekaClient, if it is another registration center, you can use the annotation @EnableDiscoveryClient to register the service

package com.springcloud.producer;

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

@SpringBootApplication
@EnableEurekaClient
public class ProducerApplication {

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

}

4. Controller

package com.springcloud.producer.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @Date:2019/7/2
 * @Time:0:02
 * @email:inwsy@hotmail.com
 * Description:
 */
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(@RequestParam String name) {
        return "hello "+name+", producer is ready";
    }
}

First, you can start the Eureka stand-alone version in the previous article, and then start the producer service provider we just wrote. After successful startup, visit the link http://localhost :8761/, You can see that our service provider producer has successfully registered in the registration center.

[ SpringCloud series tutorials| Part 3:Service provision and Feign calling

]( https://springcloud-oss.oss-c... )

At this point, the service provider has been configured.

2. Serving consumers

1. 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 http://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.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springcloud</groupId>
    <artifactId>consumers</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>consumers</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </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>

        <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>

spring-boot-starter-web: This package is a general web development package, which contains spring-web, spring-webmvc and other packages

spring-cloud-starter-openfeign: This package is the encapsulation of springcloud for Feign, Feign is a declarative Web service client. It supports Feign's own annotations, JAX-RS annotations and SpringMVC annotations. Spring Cloud integrates Ribbon and Eureka to provide a load-balanced http client when using Feign.

2. Configuration file application.yml

server:
  port:8081
spring:
  application:
    name:spring-cloud-consumers
eureka:
  client:
    service-url:
      defaultZone:http://localhost:8761/eureka/

3. Launcher ConsumersApplication.java

Same as above, add @EnableEurekaClient, if it is another registration center, you can use the annotation @EnableDiscoveryClient to register the service

package com.springcloud.consumers;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumersApplication {

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

}

@EnableFeignClients: This annotation is to inform SpringBoot to scan the class modified by @FeignClient at startup, and the @FeignClient annotation will be used when making remote calls.

4. Feign remote call

Feign is a declarative Web Service client. Using Feign can make it easier to write a Web Service client. Its use method is to define an interface, and then add annotations on it. It also supports JAX-RS standard annotations. Feign also supports pluggable encoders and decoders. Spring Cloud encapsulates Feign so that it supports Spring MVC standard annotations and HttpMessageConverters. Feign can be used in combination with Eureka and Ribbon to support load balancing.

Create a remote interface

package com.springcloud.consumers.remote;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author:shiyao.wei
 * @Date:2019/7/2 11:14
 * @Version:1.0
 * @Desc:
 */
@FeignClient(name= "spring-cloud-producer")
public interface HelloRemote {
    @RequestMapping(value = "/hello")
    String hello(@RequestParam(value = "name") String name);
}
  • name:remote service name, and the name configured by spring.application.name
  • The methods in this class must be consistent with the method names and parameters in the contoller in the remote service

5. Web layer calls remote interface Controller

package com.springcloud.consumers.controller;

import com.springcloud.consumers.remote.HelloRemote;
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;

/**
 * @Author:shiyao.wei
 * @Date:2019/7/2 11:25
 * @Version:1.0
 * @Desc:
 */
@RestController
public class HelloController {
    @Autowired
    HelloRemote helloRemote;

    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return helloRemote.hello(name);
    }
}

Now, a simple example of service registration and invocation is completed.

3. Test

Simple call

Start three projects of eureka, producer, consumer in sequence

After the startup is successful, first enter http://localhost :8080/hello?name=springcloud in the browser

You can see the page shows:hello springcloud, producer is ready

Prove that our producer has started normally and the services provided are also normal

Next, we test the service consumer and enter in the browser: http://localhost:8081/hello/spring

You can see the page shows:hello spring, producer is ready

It means that the client has successfully invoked the remote service hello through feign and returned the result to the browser.

Load balancing

Make a copy of the producer above, change the name to producer2, modify \\ in producer.2 to producer2, and modify the Controller:

package com.springcloud.producer.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @Date:2019/7/2
 * @Time:0:02
 * @email:inwsy@hotmail.com
 * Description:
 */
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(@RequestParam String name) {
        return "hello "+name+", producer2 is ready";
    }
}

Modify the application.yml configuration file startup port to 8082

Start the producer2 we just copied. At this time, you can look at the registration center Eureka. We now have two producer services.

[ SpringCloud Series Tutorials | Part 3:Service Provision and Feign Invocation

]( https://springcloud-oss.oss-c... )

At this time we will go to visit: http://localhost:8081/hello/spring

The first return result:hello spring, producer is ready

The second return result:hello spring, producer2 is ready

Continuously refresh the page, the two results will appear alternately, indicating that the registration center provides service load balancing function. Increase the number of services to N, you will find that the test results are the same, and the request will be automatically polled to each server for processing.