Micro-service across multiple service of call
Now a student and school micro-micro-service user service school, if the user needs access to school, how should we do?
1. RestTemplate way
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, the default strategy is to find linear polling service
transfer:
Result result = restTemplate.postForObject("http://SPRING-SCHOOL/school/findAll", null,Result.class); return result;
SPRING-SCHOOL is a school application name
2. Use openfeign see calls for system
The introduction of package
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
Write call-side 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); }
Start class add comments @EnableFeignClients
@SpringBootApplication @EnableEurekaClient @EnableFeignClients("com.lvlvstart.spring.demo.common.client") public class SpringUserApplication { public static void main(String[] args) { SpringApplication.run(SpringUserApplication.class, args); } }
transfer
@Autowired private SchoolClient schoolClient; @PostMapping("findAllSchool") public Result findAll(){ return schoolClient.findAll(); }
The complete code please visit: https://github.com/halouprogramer/spring-cloud-demo