Feign远程调用
本文本人亲测,未重写feign的接口,启动三个服务,feign通过远程调用controller实现
1.eruke-service(作为注册中心)
配置文件
server:
port: 1999
spring:
application:
name: eruke-service
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
default-zone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动类上面的注解
@SpringBootApplication
@EnableEurekaServer // EurekaServer作为服务器
2. eruke-client(服务提供方)
spring:
application:
name: eureka-client
server:
port: 2003
eureka:
# instance:
# hostname: localhost
instance:
preferIpAddress: true
instance-id: ${spring.application.name}:${server.port}
client:
registerWithEureka: true
fetchRegistry: false
serviceUrl:
defaultZone: http://localhost:1999/eureka/
feign远程调用的controller
package com.client.client.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class Controller {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String get() {
return "成功";
}
}
启动类注解
@SpringBootApplication
@EnableEurekaClient //注册到eureka服务器中
3.feign(远程调用)
spring:
application:
name: eureka-feign
server:
port: 2005
eureka:
# instance:
# hostname: localhost
instance:
preferIpAddress: true
instance-id: ${spring.application.name}:${server.port}
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:1999/eureka/
启动类注解
@SpringBootApplication
@EnableEurekaClient //注册到eureka服务器中
@EnableFeignClients //feign的客服端
写入一个feign的接口
package com.example.feign.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "eureka-client" )
// name为feign需要调用的远程服务名eureka-feign
//测试可用 改注解的url
public interface Feignservice {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String get() ;
}
调用feign的接口实现远程调用
package com.example.feign.service.impl;
import com.example.feign.service.Feignservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeignController {
@Autowired
Feignservice feignservice;
@GetMapping("/get")
public String get() {
return feignservice.get();
}
}
启动三个服务,发现服务注册成功
**浏览器输入: **http://localhost:2005/get 调用启动调用feign的远程接口
测试eruke-client可输入http://localhost:2003/get
如果抛出com.netflix.client.ClientException: Load balancer does not have available server for client: xxx异常
解决办法: 将feign服务 fetchRegistry改为 true
网上有的在 服务里面加入了
ribbon.eureka.enable: true
``
来开启负载均衡,我使用无效,大部分网友测试有效,可能因为环境问题我先放在这里