Springcloud03服务消费者

浅浅的花香味﹌ 2022-05-24 02:08 320阅读 0赞
  1. 服务提供者和消费者在注册中心中并没有绝对的界限,上一章中提到服务的提供者其实在项目的应用中,很多情况都会涉及的服务间的相互调用。在一般的微服务架构中服务与服务之间的通讯是一种常见的情况,而这种通讯一般是基于http restful的。
  2. 老步骤:

pom文件一次增加:

  1. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-eureka-server</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-ribbon</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-web</artifactId>
  13. </dependency>

application.yml文件:

  1. eureka:
  2. client:
  3. serviceUrl:
  4. defaultZone: http://localhost:8761/eureka/
  5. server:
  6. port: 8764
  7. spring:
  8. application:
  9. name: service-ribbon

启动入口ServiceRibbonApplication:

  1. /**
  2. * 通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;
  3. * 并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
  4. */
  5. @SpringBootApplication
  6. @EnableDiscoveryClient
  7. @ComponentScan(value="com.example")
  8. public class ServiceRibbonApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(ServiceRibbonApplication.class, args);
  11. }
  12. @Bean
  13. @LoadBalanced
  14. RestTemplate restTemplate() {
  15. return new RestTemplate();
  16. }
  17. }
  18. 这里解释下使用@ComponentScan(value="com.example")的原因,受之前SSH的开发模型影响,定义Controler文件的时候会单独分包,然后问题就出现了,我怎么也访问不到自己的Controler,这里就很尴尬了,导入都正常,就是访问报错。后来查询在发现:**SpringBoot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象,如果当前启动类没有包,则在启动时会报错。 因为启动类不能直接放在main/java文件夹下,必须要建一个包把它放进去或者使用@ComponentScan指明要扫描的包。**基本上就是这样的,其实也可以自己测试一下,多写两个文件自测一下就可以了。

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

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

HelloService文件:

  1. @Service
  2. public class HelloService {
  3. @Autowired
  4. RestTemplate restTemplate;
  5. public String hiService(String name) {
  6. return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
  7. // return "hi "+name+",i am from port: 8764";
  8. }
  9. }

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

相互学习!!!

发表评论

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

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

相关阅读

    相关 Springcloud03服务消费者

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