我們要新建一個springboot服務,user-consumer 除了和之前創建eureka-client步驟都一樣以外還需要勾選feign支持
我們在eureka-client中加入代碼
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserService { @GetMapping("/login") public String login(){ return "success1"; } }
再到user-consumer中
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class UserConsumerApplication { public static void main(String[] args) { SpringApplication.run(UserConsumerApplication.class, args); } } 啓動類要加入@EnableFeignClients註解,下面我們做個小栗子,
import com.example.userconsumer.userService.impl.UserServicImpl; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name="eureka-client") public interface UserService { @GetMapping("/login") String login(); }
我們寫一個藉口,加上@FeignClient註解,name值就是eureka-client服務的名
接下來我們作一個模擬登陸的類,
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Longin { @Autowired private UserService userService; @GetMapping("/userLogin") public String longin(){ return userService.login(); } }
把接口注入,然後調用login方法,這樣就實現了遠程調用