Spring Cloud多个微服务之间调用代码实例
人气:0这篇文章主要介绍了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(); }
完整代码请访问: https://github.com/halouprogramer/spring-cloud-demo
您可能感兴趣的文章:
加载全部内容