导入包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
写一个api 为什么要写api导入到provider和consumer 是因为这样就比较方便controller直接调用,不用自己写,
其实也可以不用这个方法,也可以不封装这个userapi类,直接写
public interface RegisterApi {
@GetMapping("/user/isAlive")
public String isAlive();
}
maven install 然后把包导入到user-provider 这个是新建立的项目
<dependency>
<groupId>com.example</groupId>
<artifactId>user-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
写provider的controller 因为这就一个方法可以直接实现,就不用写service
@RestController
public class MyController implements RegisterApi {
@Override
public String isAlive() {
return "ok";
}
}
注册到eureka
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
server:
port: 8084
spring:
application:
name: user-provider
在consumer里面 写调用方法
@FeignClient(name = "user-provider")
public interface UserService extends RegisterApi {
}
加上注解--就是服务名 这样比用resttemplate 调用方便就是不用自己拼接url,
注册
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
server:
port: 8085
spring:
application:
name: user-consumer
最后加上controller
@RestController
public class MyController {
@Autowired
UserService userService;
@GetMapping("/alive")
public String alive(){
return userService.isAlive();
}
}
关键就是这个啊 这个注解一定要加,不用就没用
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);
}
}