Overview
In the Spring Cloud EureKa Ribbon service registration-discovery-call article, a brief introduction to how to use EureKa and Ribbon in Spring Cloud. The article uses RestTemplate to access other restful microservice interfaces. In fact, in Spring Cloud, you can also use Feign to access other restful microservice interfaces. It is more concise and clear to use.
Integrated Feign
Change the pom configuration of the order service in the Spring Cloud EureKa Ribbon service registration-discovery-call call, and just introduce Fegin.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId></dependency>
Modify the OrderApplication class and delete the following code:
@Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }And add @EnableFeignClients annotation. The complete code is as follows:
package com.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.feign.EnableFeignClients;@EnableDiscoveryClient@EnableFeignClients@SpringBootApplicationpublic class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); }}Added the interface UserService and use @FeignClient annotation.
package com.springboot;import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;@FeignClient(name="user")public interface UserService { @GetMapping(value="/getUser") String getUser();}The name=user in @FeignClient(name="user") here means you want to access the user microservice. Since the order microservice has integrated Eureka and Ribbon. Then when using @FeignClient(name="user") to access the user microservice, client routing has been automatically supported. And the micro service user will be found in the registry.
Modify the OrderController and inject the UserService.
package com.springboot;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class OrderController { @Autowired private UserService userService; @GetMapping("/getOrderUser") public String getOrderUser() { return userService.getUser(); }}This way there is no need to use it
restTemplate.getForEntity("http://user/getUser",String.class).getBody();To call the getUser interface in the user service. Instead, just use userService.getUser().
Start the registry center and the two micro services of user and order. Use http://localhost:8883/getOrderUser
Visit it. Yes, you can return
I am user list.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.