SpringCloud中项目因为是一个个小的项目,所以项目(模块)之间怎样访问就成了问题?
有两种方式:
第一种:使用RestTemplate方式来调用服务端的接口
步骤1:在子模块的启动类同目录下加一个类,名字随便起(我的是RestConfig),代码附下
@Configuration
public class RestConfig {
@Bean
//@LoadBalanced //Ribbon负载均衡(手动开启)
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
步骤2:.在controller中注入RestTemplate
@Autowired
private RestTemplate restTemplate;
步骤3:在调用的方法内写下面的两行代码
String url="http://localhost:7201/provider/hello";---需要调用的模块路径
String message = restTemplate.getForObject(url, String.class);
然后调用即可
注:在启动类EurekaConsumer01Application.java上添加@EnableEurekaClient注解,点击运行即可,
注意不要关闭之前启动的eureka-server/eureka-provider
第二种:使用Fegin方式来调用服务端的接口
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。
它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。
Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
首先在父模块中导入Fegin的架包,子模块继承父模块
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
因为Fegin是通过接口的方式调用,所有需要在子模块中新建一个(services)接口包,在里面写接口
步骤1:在接口包中新建一个接口HelloFegin
@Service
@FeignClient("eureka-provider")//eureka-provider即生产者在注册中心注册的名字
//在该调用中,我们feign并不需要指定端口号,它并不知道这个方法所在的服务提供者现在在哪个端口运行,我们只需要向eureka寻求服务。
public interface HelloFeigin {
//这里是需要调用子项目中的哪个方法
@RequestMapping("/provider/hello")
String hello();
}
步骤2:调用的controller中注入HelloFeigin接口类,然后方法中直接调用
@RestController
public class TestConController {
@Autowired
private HelloFegin helloFegin;//注入
@RequestMapping("test02/{name}")
public String TestCom(@PathVariable String name){
System.out.println("消费者02" + name);
String s = helloFegin.testpro(name);
System.out.println(s);
return s;
}
}
步骤3:也是最重要的一步
在启动类EurekaConsumer02Application.java上添加@EnableEurekaClient和@EnableFeignClients注解,点击运行即可
注:FeignClient接口,不能使用@GettingMapping 之类的组合注解
FeignClient接口中,如果使用到@PathVariable ,必须指定其value
@PathVariable("name") 中的"name",不能省略,必须指定