Springcloud03服务消费者

本文介绍了微服务架构中服务间基于HTTP RESTful的通信方式,并详细讲解了如何使用Spring Cloud搭建Eureka服务注册中心,包括pom文件配置、application.yml设置及启动类的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    服务提供者和消费者在注册中心中并没有绝对的界限,上一章中提到服务的提供者其实在项目的应用中,很多情况都会涉及的服务间的相互调用。在一般的微服务架构中服务与服务之间的通讯是一种常见的情况,而这种通讯一般是基于http restful的。

    老步骤:

pom文件一次增加:

   <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

application.yml文件:

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon

启动入口ServiceRibbonApplication:

/**
 * 通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;
 * 并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
 */
@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(value="com.example")
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceRibbonApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

    这里解释下使用@ComponentScan(value="com.example")的原因,受之前SSH的开发模型影响,定义Controler文件的时候会单独分包,然后问题就出现了,我怎么也访问不到自己的Controler,这里就很尴尬了,导入都正常,就是访问报错。后来查询在发现:SpringBoot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象,如果当前启动类没有包,则在启动时会报错。 因为启动类不能直接放在main/java文件夹下,必须要建一个包把它放进去或者使用@ComponentScan指明要扫描的包。基本上就是这样的,其实也可以自己测试一下,多写两个文件自测一下就可以了。

同目录下是不用增加@ComponentScan注解的。

对应文件HelloControler参照上一章内容即可:

HelloService文件:

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
//        return "hi "+name+",i am from port: 8764";
    }
}

以上步骤和内容部分来自《深入理解Spring Cloud与微服务构建》 作者:方志朋。

相互学习!!!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值