Springcloud03服务消费者
服务提供者和消费者在注册中心中并没有绝对的界限,上一章中提到服务的提供者其实在项目的应用中,很多情况都会涉及的服务间的相互调用。在一般的微服务架构中服务与服务之间的通讯是一种常见的情况,而这种通讯一般是基于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与微服务构建》 作者:方志朋。
相互学习!!!
还没有评论,来说两句吧...