Spring cloud calls code instances between multiple microservices

Time:2021-7-27

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;

@Configuration
public class RestTempldateConfig {
  @Bean
  @Scope("singleton")
  @LoadBalanced
  public RestTemplate restTempldate(){

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

    return restTemplate;
  }

}

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

Call:


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


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

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;

@FeignClient("SPRING-SCHOOL")
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


@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients("com.lvlvstart.spring.demo.common.client")
public class SpringUserApplication {

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

}

call


@Autowired
private SchoolClient schoolClient;

@PostMapping("findAllSchool")
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.