Ribbon of Spring Cloud, Spring RestTemplate call service

On the basis of the Eureka Server cluster , using Spring RestTemplate, combined with the Ribbon function for service invocation, the usage is very simple.

1. Create a new module in the main project, eurekaclient, maven dependency,

<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.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

2. The application.yml configuration file,

spring:
  application:
    name: eurekaclient
server:
  port: 8080
  shutdown: graceful
eureka:
  client:
    service-url:
      defaultZone: http://peer1:8761/eureka/

 

3. Define RestTemplate in the startup class, and support Ribbon to enable load balancing through Spring Cloud's @LoadBalanced annotation.

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

4. Develop an interface in the logservice service for the eurekaclient service to call,

@RestController
@RequestMapping("log")
public class LogController {

    @GetMapping("logInfo")
    public String logInfo(String logInfo) {
        System.out.println(logInfo);
        return logInfo;
    }

}

5. Define a Service class in eurekaclient, add it to the container through the @Component annotation, and use restTemplate to call the logservice service.

@Component
public class LogServiceClient {

    @Autowired
    private RestTemplate restTemplate;

    public String logInfo(String logInfo) {
        return restTemplate.getForObject("http://logservice/log/logInfo?logInfo="+logInfo, String.class);
    }

}

Define the interface in eurekaclient, call the logInfo method of the Service class in step 5,

@RestController
@RequestMapping("client")
public class TestController {
    @Autowired
    private LogServiceClient logServiceClient;

    @GetMapping("getClientInfo")
    public String getClientInfo() {
        String info = "log info";
        return logServiceClient.logInfo(info);
    }
}

6. Enter the interface address defined in eurekaclient in the browser, http://localhost:8080/client/getClientInfo

 

7. It is also very convenient to test Ribbon load balancing, only need to start multiple instances of logservice

 

 

 

 

Guess you like

Origin blog.csdn.net/suoyx/article/details/114102636