一、微服务架构如下:
模块名 | 用途 | 实例名 |
springCloud_nacos | 服务注册中心 | springcloud-nacos |
springCloud_serviceA | 微服务模块A | springcloud-serviceA |
springCloud_serviceB | 微服务模块B | springcloud-serviceB |
二、openFeign实现微服务间接口调用(serviceA 调用 serviceB 接口)
1、在父pom.xml中添加依赖
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2、serviceB 提供方配置:
1)Controller层:
@RestController
@RequestMapping("/serverB")
public class SerBController {
@Autowired
SerBService serBService;
@GetMapping("/queryByName/{userName}")
public String queryByName(@PathVariable String userName){
return serBService.queryByName(userName);
}
}
2) Service层:
public interface SerBService {
String queryByName(String userName);
}
3)接口实现类:
@Service
public class SerBServiceImpl implements SerBService {
@Override
public String queryByName(String userName) {
return "恭喜你成功调用serviceB接口,名称为:" + userName;
}
}
3、serviceA 调用方配置:
1)在启动类中添加注解@EnableFeignClients,代码如下:
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@RibbonClient(name = "springcloud-serviceA")
@EnableFeignClients
public class SpringCloudServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudServiceAApplication.class, args);
}
}
2)Controller层:
@RestController
@Slf4j
@RequestMapping("/serverA")
public class CommonController {
@Autowired
private CommonService commonService;
@GetMapping("/queryServiceB/{userName}")
public String queryServiceB(@PathVariable String userName) {
return commonService.queryServiceB(userName);
}
}
3)Service层:
@FeignClient(name = "springcloud-serviceB")
public interface CommonService {
@GetMapping("/serverB/queryByName/{userName}")
String queryServiceB(@PathVariable String userName);
}
注:① 接口层添加注解@FeignClient,并在注解中指明属性value="服务提供方的实例名";
② 在方法上添加映射的URL要与服务提供方接口的URL一致;
三、测试
使用postman测试,调用serviceA 的接口,查看serviceA能否跨模块调用serviceB的接口
请求URL:
http://216.1.1.7:9903/serverA/queryServiceB/张三
返回结果:
恭喜你成功调用serviceB接口,名称为:张三