Import packages

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
Copy the code

Write an API and the reason why you want to write an API and import it into the provider and consumer is because it’s easier for the controller to call it directly instead of writing it,

You can do this without using this method, or you can write the userAPI class without encapsulating it

public interface RegisterApi {

	@GetMapping("/user/isAlive")
	public String isAlive(a);

}
Copy the code

Maven install then imports the package into user-provider, which is the newly created project

 <dependency>
            <groupId>com.example</groupId>
            <artifactId>user-api</artifactId>
            <version>0.01.-SNAPSHOT</version>
        </dependency>
Copy the code

Write the controller of the provider because there is only one method that can be implemented directly instead of writing the Service

@RestController
public class MyController implements RegisterApi {

	@Override
	public String isAlive(a) {
		return "ok"; }}Copy the code

Registered to eureka

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
server:
  port: 8084

spring:
  application:
    name: user-provider
Copy the code

Write the call method in consumer

@FeignClient(name = "user-provider")
public interface UserService extends RegisterApi {}Copy the code

Annotating — that’s the name of the service so it’s easier to call than restTemplate because you don’t have to concatenate the URL yourself,

registered

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
server:
  port: 8085

spring:
  application:
    name: user-consumer
Copy the code

And then finally the controller

@RestController
public class MyController {
	@Autowired
	UserService userService;

	@GetMapping("/alive")
	public String alive(a){
		returnuserService.isAlive(); }}Copy the code

That’s the point. This annotation must be added. If you don’t use it, it won’t work

package com.example.userconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class UserConsumerApplication {

	public static void main(String[] args) { SpringApplication.run(UserConsumerApplication.class, args); }}Copy the code