springboot整合nacos注册中心以及openFeign服务调用
引入依赖
这其中可能会存在nacos和springboot的版本依赖问题,可以网上搜下
如果相互之间版本对不上,会存在很多奇奇怪怪的问题
本次使用的版本为以下内容
- 查询版本的时候可以现根据你的SprinBoot版本,查询对应的SpringCloud版本,然后通过SpringCloud版本查找适配的Nacos版本,以此规则往后推出其余需要的版本
<!--springboot的版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--nacos依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!--openFeign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
配置项目注册的nacos地址
# 服务启动端口
server:
port: 8000
spring:
application:
# 服务注册进nacos时使用的服务名
name: runtest
cloud:
# 服务注册进入的nacos地址
nacos:
discovery:
server-addr: 127.0.0.1:8848
启动项目
登录进入nacos地址IP:8848/nacos
,默认用户名密码都为nacos,查看服务管理中的服务列表中,自己的服务是否已经注册进入nacos
OpenFeign
暴露接口准备
首先要有一个自己需要暴露出去的接口
以下是一个正常的API接口
@RestController
@RequestMapping("/AOP")
public class AOPController {
@AOPAnnotationConfig
@GetMapping("/getOne")
public String getOne(@RequestParam Integer id,@RequestParam String name,@RequestParam Integer error) throws Exception{
if(error == 1){
throw new Exception("error异常输出");
}
String result = name+id;
return result+"---------------------------------";
}
}
配置OpenFeign
openFeign可以在服务端配置,之后连带着服务端一起打包提供给外部使用
也可以在客户端配置,使用客户端直接访问
前提是服务端和客户端都可以注册进入同一个Nacos,且在用一个组下才能互相发现调用
启动类
在启动类上添加相应的注解开启OpenFeign功能
@EnableFeignClients
接入入口
起一个接口
@FeingClinet
指定需要调取的服务在nacos中注册的服务名
其中声明的接口的HTTP
方法声明,以及入参内容,返回值必须和原本的服务提供方所提供的结构保持一致,否则会存在调取不成功的结果
@FeignClient(value = "runtest")
@Service
public interface OpenFeignService {
@GetMapping("/AOP/getOne")
String getOne(@RequestParam Integer id, @RequestParam String name, @RequestParam Integer error);
}
声明一个调用类
引入上述的OpenFeign的接口调用,直接使用其中的方法即可完成对服务提供方的方法调用
@RestController
@RequestMapping("/openfeign")
public class OpenFeignController {
@Resource
private OpenFeignService openFeignService;
@PostMapping("/getOne")
public String getOne(@RequestParam Integer id, @RequestParam String name, @RequestParam Integer error){
String one = openFeignService.getOne(id, name, error);
return one;
}
}