前提版本:SpringBoot :2.1.9 spring-cloud.version:Greenwich.SR3
Feign:声明式服务调用,整合了Ribbon和Hystrix。
1、新建SpringBoot项目feign-client,pom引入eureka和feign:
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Feign声明式服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、启动类添加注解@EnableFeignClients和 @EnableDiscoveryClient。
3、创建FeignService接口,注意:是接口!!接口上加@FeignClient(value = "ZHZY")注解,value是要调用的eureka注册中心的服务。不区分大小写!
package com.smiletou.sweet.dream.service;
import com.smiletou.sweet.dream.result.ResponseMessage;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Feign声明式服务调用
*
* @author ZHANGCHAO
* @date 2019/11/5 14:32
* @since 1.0.0
*/
@FeignClient(value = "ZHZY")
public interface FeignService {
@PostMapping(value = "/core/user/login")
ResponseMessage login(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("node") String node,
@RequestParam(value = "force", required = false) String force);
}
4、创建ConsumerController,注入FeignService。
package com.smiletou.sweet.dream.controller;
import com.smiletou.sweet.dream.entity.SysUser;
import com.smiletou.sweet.dream.result.ResponseMessage;
import com.smiletou.sweet.dream.service.FeignService;
import com.smiletou.sweet.dream.service.RibbonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/**
* @author ZhangChao
* @date 2019/10/31 14:44
* @since 1.0.0
*/
@RestController
public class ConsumerController {
@Autowired
private FeignService feignService;
/**
* Feign方式调用服务
*
* @param username
* @param password
* @param node
* @param force
* @return
*/
@PostMapping("/login")
public ResponseMessage login(String username, String password, String node, String force){
return feignService.login(username,password,node,force);
}
}
5、application.properties配置文件:
server.port=8088
spring.application.name=sweet-dream
eureka.client.serviceUrl.defaultZone=http://115.129.143.133:1111/eureka/,http://115.129.143.133:1112/eureka/
6、启动项目,通过postman调用localhost:8088/login?username=ceshi&password=f379eaf3c831b04de153469d1bec345e&node=dn59即可。