Spring cloud calls code instances between multiple microservices


This article mainly introduces the calling code examples between multiple microservices in spring cloud. The example code is introduced in great detail, which has certain reference value for everyone’s study or work. Friends in need can refer to it

Now there is another student micro service user and school micro service school. What should we do if the user needs to access the school?

1. Use resttemplate method

Add config

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestTempldateConfig {
  public RestTemplate restTempldate(){

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    return restTemplate;


@Loadbalanced is a load balancing annotation. By default, the service is found by linear polling strategy


Result result = restTemplate.postForObject("http://SPRING-SCHOOL/school/findAll", null,Result.class);
return result;

Spring-school is the name of the school application

2. Use openfeign to realize system call

Import package


Write caller code

import com.lvlvstart.spring.demo.common.entity.School;
import com.lvlvstart.spring.demo.common.msg.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

public interface SchoolClient {

  @PostMapping(value = "/school/findAll")
  public Result<List<School>> findAll();

  @PostMapping(value = "/school/findById")
  public Result<School> findById(String schoolId);

Add annotation @ enablefeignclients to startup class

public class SpringUserApplication {

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



private SchoolClient schoolClient;

public Result findAll(){
  return schoolClient.findAll();

For the complete code, please visit:   https://github.com/halouprogramer/spring-cloud-demo

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.