SpringCloud realizes communication between Microservices through Feign
Maven coordinates of dependent class libraries:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
Version number
</dependency>
Brief introduction:
Spring Cloud Feign is a declarative HTTP client developed based on Netflix Feign, which is used to simplify communication between Microservices. It can convert RESTful service calls into method calls of interfaces, and achieve inter service calls through built-in load balancing strategies.
Implement a complete example (suppose there are two Microservices: User Service and Order Service):
Firstly, add Feign's dependency to the pom.xml of User Service:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
Version number
</dependency>
Then, add the @ EnableFeignClients annotation on the startup class of the User Service:
@SpringBootApplication
@EnableFeignClients
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
Next, create a Feign interface in User Service to define the method for calling Order Service:
@FeignClient (name="order service")//Specify the name of the service to be called
public interface OrderServiceClient {
@GetMapping ("/orders/{orderId}")//Define the interface method to be called
Order getOrderById(@PathVariable("orderId") Long orderId);
}
In the above code, we use the @ FeignClient annotation to specify the service name to be called, and the @ GetMapping annotation to define the interface method to be called.
Finally, in the business logic of User Service, use the Feign interface to call the Order Service:
@Service
public class UserService {
@Autowired
private OrderServiceClient orderServiceClient;
public Order getOrderById(Long orderId) {
return orderServiceClient.getOrderById(orderId);
}
}
Through the above code, we can directly call the getOrderById method of Order Service in User Service.
Finally, you can start the User Service and Order Service, and use the UserService to call the OrderServiceClient method to achieve communication between Microservices.
Summary:
Spring Cloud Feign simplifies the communication between Microservices by using the Feign interface, and converts RESTful service calls into interface method calls, making the code more concise and readable. By defining the Feign interface and specifying the name of the service to be called with the @ FeignClient annotation, we can directly call the method of another Microservices in one Microservices, thus realizing the communication between Microservices.