最近在项目中使用到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