- 模块与模块之间内部的相互调用访问请求获取需要的数据
- 对外需要暴露接口的服务模块中配置
- 模块结构
-
添加依赖坐标
org.springframework.cloud spring-cloud-starter-openfeign -
编写对应producer-server中controller对应需要对外暴露接口
controller中接口 编写feign对外暴露接口(FeignClient值为yml中注册中心服务名)
- 在需要使用该暴露接口的服务模块中添加配置
- 模块结构
- 添加依赖坐标
io.github.openfeign
feign-httpclient
org.example
producer-api
1.0-SNAPSHOT
2. 添加启动类注解
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(ConsumerApplication.class, args);
}
}
- 编写yml配置文件
server:
port: 8099
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
application:
name: consumerService # 注册中心服务名称
main:
allow-bean-definition-overriding: true
feign:
client:
config:
default:
connectTimeout: 10000
readTimeout: 10000
loggerLevel: basic
httpclient:
enabled: true # 支持HttpClient的开关
max-connections: 200 # 最大连接数
max-connections-per-route: 50 # 单个路径的最大连接数
logging:
level:
root: INFO
org.springframework.web.servlet.DispatcherServlet: DEBUG
org.springframework.cloud.sleuth: DEBUG
在consumer模块中调用访问对外暴露接口获取参数请求
- service层
@Service
public class ConsumerService {
@Autowired
private ProducerFeignClient producerFeignClient;//对外暴露服务接口
public String getHello(){
return producerFeignClient.hello();
}
}
2.controller层
@RestController
@RequestMapping("consumer")
public class ConsumerController {
@Autowired
private ConsumerService consumerService;
@RequestMapping("/hello")
public String hello() {
return "feign:" + consumerService.getHello();
}
}
测试请求结果
二、使用RestTemplate方式
- 在启动类中创建RestTemplate容器
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(ConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- 在service使用RestTemplate进行远程接口访问
@Service
public class ConsumerService {
@Autowired
private RestTemplate restTemplate;
public String getHello(){
//http://注册中心服务名/controller名/接口名
String url = "http://producerService/producer/hello";
return "RestTemplate:" + restTemplate.getForObject(url, String.class);
}
}
- 测试请求结果



