Spring Cloud 服务之间调用

 

微服务之多个服务间调用

现在又一个学生微服务 user 和 学校微服务 school,如果user需要访问school,我们应该怎么做?


1.使用RestTemplate方式

添加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是一个负载均衡注解,默认是线性轮询策略找到服务


调用:

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


 

SPRING-SCHOOL 为school应用名称


2.使用 openfeign 实现系统见调用

 

引入包

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

 

编写调用端代码

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);
}

 

启动类添加注解 @EnableFeignClients

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

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

}

 

调用

@Autowired
private SchoolClient schoolClient;

@PostMapping("findAllSchool")
public Result findAll(){
  return schoolClient.findAll();
}

 

openfeign 设置调用超时时间

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic

 

为什么 openfeign 的超时时间是 connectTimeout 和 readTimeout ?有知道的可以在评论区告诉我


完整代码请访问: https://github.com/halouprogramer/spring-cloud-demo

posted on 2019-12-16 17:54  指尖,写不尽  阅读(432)  评论(0编辑  收藏  举报

导航