上一篇博客我们讲了如何去创建注册中心并注册服务,那注册中心的服务我们要如何去调用呢?这里我们先使用Feign声明式服务调用,这里以UserController去调用DictionaryController里的服务
1.引入依赖:
<!-- Feign声明式服务调用依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
2.开启Feign,主方法必须要配置两个注解:
@EnableDiscoveryClient
@EnableFeignClients
3.创建一个服务调用接口:
package com.id0304.user.feign;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
@Service //注入spring容器
@FeignClient("dictionary") //这里写服务名称,即spring-application-name配置的属性名称
public interface FeignService {
@GetMapping("/hello") //这里写对应服务的url
public String hello();
}
4.在UserController调用DictionaryController的hello方法
UserController:
package com.id0304.user.controller;
import com.id0304.user.feign.FeignService;
import com.id0304.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@Autowired
UserService userService;
@Autowired
FeignService feignService; //注入该对象,即可调用
@GetMapping("/test")
public @ResponseBody String test(){
return feignService.hello(); //调用hello方法,实际上就是远程调用了DictionaryService里的hello方法
}
}
DictionaryController:
package com.id0304.dictionary.controller;
import com.id0304.common.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DictionaryController {
@GetMapping("/hello") //这里的url要跟上面Feign接口调用的url一致
public @ResponseBody String hello() { //可以给UserController调用
return "hello!";
}
}