项目的DEMO代码:https://github.com/heyu52/-spring-cloud
系统一般不会只有一个项目,如果有多个模块,那这些模块之间,调用是一个问题,接下来,我讲讲最简单的调用方式Feign。
我们先再创建一个服务模块goodspr
创建后,goodspr中也增加一个服务方法
package com.csdn.GoodsPR.web;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class homeController {
@RequestMapping("/home/{name}")
public String home(@RequestParam(value = "name", defaultValue = "csdn") String name)
{
return "这是需求服务"+"参数:"+name;
}
}
启动类中增加注解EnableDiscoveryClient
package com.csdn.GoodsPR;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GoodsPrApplication {
public static void main(String[] args) {
SpringApplication.run(GoodsPrApplication.class, args);
}
}
在配置中增加
server.port=8765
spring.application.name=GoodsPR
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.prefer-ip-address=true
# 实例名称 最后呈现地址
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#启用监控
management.endpoints.web.exposure.include=*
#显示健康详细信息 默认不显示详细信息
management.endpoint.health.show-details=always
接下来,我们到网关服务中把这个模块加上
#GOODSPR加入网关
zuul.routes.GOODSPR.service-id=GOODSPR
先启动服务中心,再启动其他模块,最后:http://127.0.0.1:8761/
接下来,我们使用feign通过goodspo访问goodspr的服务
首先我们在goodspo中增加引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
定义调用接口
package com.csdn.GoodsPO.RestfulRemote;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name= "GOODSPR")
public interface GoodsPRRemote {
//restful api 调用
@GetMapping("/home/{name}")
public String home(@PathVariable("name") String name);
}
控制器中增加调用
@Autowired
GoodsPRRemote goodsPRRemote;
@RequestMapping("/getGoodspr")
public String getGoodspr(@RequestParam(value = "name", defaultValue = "csdn") String name) {
return goodsPRRemote.home(name);
}
启动类中增加注解@EnableFeignClients
package com.csdn.GoodsPO;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class GoodsPoApplication {
public static void main(String[] args) {
SpringApplication.run(GoodsPoApplication.class, args);
}
}
启动项目,输入地址:http://127.0.0.1:8762/goodspo/getGoodspr
测试成功,通过goodspo访问了goodspr。