在使用spring cloud进行日常开发过程中,会到遇到需要集成已有的一些服务或者第三方服务,但这些服务并未使用eureka管理,在使用spring-cloud-feign集成时与集成受eureka管理服务使用方式有差别,以下为相关要点记录
该项目使用gradle管理依赖,相关配置如下:
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.example.cloud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Dalston.SR4'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-starter-eureka')
compile('org.springframework.cloud:spring-cloud-starter-feign')
compile('org.springframework.cloud:spring-cloud-starter-hystrix')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
当前使用服务为微服务,需要注册到eureka上,以提供给其它微服务调用,并且该服务需使用feign集成其它第三方服务,application.yml内容如下:
#name
spring:
application:
name: sample-service
#eureka config
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
主类配置如下:
@EnableDiscoveryClient //启用服务发现客户端
@SpringBootApplication
@EnableFeignClients //启用feignClient
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
其中该服务中需要使用feign额外调用外部的A服务,A服务非eureka管理,不能通用eureka注册的服务ID进行访问,该服务完整地址为:http://service-a.example.com/v2/sms/singleSend
相关使用代码如下:
@FeignClient(name = "a-service", url = "http://service-a.example.com/")
public interface ServiceAFeign {
@RequestMapping(value = "/v2/sms/singleSend", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_FORM_URLENCODED)
public SendResponse singleSend(@RequestParam("mobile") String mobile,
@RequestParam("text") String text);
}
重点关注@FeignClient
中的配置项,其中name
属性值不应该与eureka上注册的其它服务相同,以免导致feign无法正确调用,url
属性值需要配置为实际调用的地址,以上两个配置项缺一不可,如未设置url
属性值,只设置了name
,feign会到eureka中去找注册的服务,但实际无法找到,导致无法正常调用,以上为踩坑过程。