springcloud使用restTemplate进行服务调用

客官°小女子只卖身不卖艺 2023-10-18 22:53 178阅读 0赞

在springcloud的体系中,微服务之间的互相调用是其中比较重要的模块之一,也是微服务的rpc主要核心板块,我们熟知的用于微服务互相调用的组件像ribbon和feign便是其中之一,但在谈到这两个组件之前,我想先使用一下restTemplate,即springboot的web模块提供的一款内置的http通信组件,

接着之前的demo,我们再创建一个微服务的模块,作为consumer端,使用restTemplate调用上一篇provider中的接口,

pom依赖基本相同,配置文件略有差异,直接贴上代码,

  1. server.port=8102
  2. #挂载到eureka注册中心中的服务名称,以便被其他的消费者发现与引用
  3. spring.application.name=consumer1
  4. #注册中心名字
  5. eureka.client.service-url.defaultZone=http://localhost:8100/eureka
  6. ### 需要将自己的服务注册到eureka上
  7. eureka.client.register-with-eureka=true
  8. ####需要检索服务
  9. eureka.client.fetch-registry=true

创建一个测试使用的controller,

  1. @RestController
  2. public class ConsumerController {
  3. // RestTemplate 是有SpringBoot Web组件提供 默认整合ribbon负载均衡器
  4. // rest方式底层是采用httpclient技术
  5. @Autowired
  6. private RestTemplate restTemplate;
  7. /**
  8. * 在SpringCloud 中有两种方式调用 rest、fegin

发表评论

表情:
评论列表 (有 0 条评论,178人围观)

还没有评论,来说两句吧...

相关阅读