微服务之多个服务间调用
现在又一个学生微服务 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
原文地址:https://www.cnblogs.com/haloujava/p/12050399.html
时间: 2024-10-09 10:42:00