spring cloud feign使用实例

本文详细介绍了如何在SpringCloud项目中整合Feign和Consul进行微服务调用和服务注册。通过实例展示了依赖配置、代码实现及配置文件设置,帮助读者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在项目中使用到http接口调用,需要用到spring cloud feign,记录下。

首先在本地安装consul注册中心,需要将相关服务注册到consul,详见我的另一篇文章。

相关依赖:

<!-- SpringCloud-Consul -->
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-consul-discovery</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      <!-- SpringCloud-OpenFeign -->
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-openfeign</artifactId>
      </dependency>

服务提供方代码:

需要在启动类上加上这两个注解:

@EnableDiscoveryClient
@EnableFeignClients

提供一个普通的controller:

@RestController
@RequestMapping("/command")
public class CommandController
{
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CommandController.class);

    @Autowired
    private ICommandService commandService;

    @Autowired
    WebSocketServer webSocketServer;

    /**
     * <传输指令>
     *
     * @param checkCommand checkCommand
     * @return 结果
     * @throws
     */
    @RequestMapping(value = "/transferCommand", method = RequestMethod.POST)
    public ResultEntity<Boolean> transferCommand(@RequestBody CheckCommand checkCommand)
    {
        try
        {
            LOGGER.info(
                "[ConsumeCommandTask] id is {}, type is {}, input is {}, output is {}, start is {}, end is {}, time is {}.",
                checkCommand.getId(), checkCommand.getType(), checkCommand.getInput(),
                checkCommand.getOutput(), checkCommand.getStart(),
                checkCommand.getEnd(), checkCommand.getTimes());
            webSocketServer.sendToAll(CommandSerializer.serialize(checkCommand));
//            return commandService.transferCommand(checkCommand);
        }
        catch (Exception e)
        {
            LOGGER.error("传输指令失败,原因:", e);
            return ResultEntity.fail("400", "数据异常");
        }

        return ResultEntity.success(true);
    }
}

配置文件:

# spring 配置 注册springcloud时候的服务名称,在下面serviceName使用
spring.application.name=cmdserver

# consul集群相关配置
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
# 服务发现配置
# 注册服务打开
spring.cloud.consul.discovery.register=true
# 服务名称
spring.cloud.consul.discovery.serviceName=${spring.application.name}
# 开启服务健康检查
spring.cloud.consul.discovery.healthCheckPath=/actuator/health
# 检查间隔
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.tags=urlprefix-/${spring.application.name}
# 服务唯一标识
spring.cloud.consul.discovery.instanceId=${spring.application.name}:aa356dsfe21312fafd00asdf

服务调用方代码:

@Headers({"Content-Type: application/json", "Accept: application/json"})
@FeignClient(name = "cmdserver", url = "${spring.cloud.consul.discovery.ip-address}")
public interface VideoDao
{
    @RequestMapping(value = "/command/transferCommand", method = RequestMethod.POST)
    public ResultEntity<Boolean> transferCommand(CheckCommand checkCommand);
}

在service层调用上述代码即可。

同时在启动类上需要加上注解:

@EnableFeignClients
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值