步骤
- 在原有消费者项目中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
- 创建Service接口
创建的Service接口加上@Service
注解自动生成实现类,并添加@FeignClient
注解,value参数值是需要调用的服务名称;在接口方法上加上对应的请求,务必与提供服务的接口请求一致才能获取到数据。
@Service
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface testFeign {
@RequestMapping("/getDepts")
List<dept> testFeign();
}
- 开启Feign功能
在启动类上追加@EnableFeignClients注解,packages的参数是Service所在的包。注:@RibbonClicent注解是实现负载均衡的,如果没有配置则可省略。
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = MyRule.class)
@EnableFeignClients(basePackages = {"com.example.springcloudconsumerdept8088.Service"})
public class SpringcloudConsumerDept8088Application {
public static void main(String[] args) {
SpringApplication.run(SpringcloudConsumerDept8088Application.class, args);
}
}
- 调用服务
服务的调用直接调用Service提供的方法即可
@RestController
public class DeptController {
@Autowired
testFeign testFeign;
@RequestMapping("/getDepts")
public List<dept> getDepts(){
return testFeign.testFeign();
}
}