赞
踩
使用技术:nacos注册表、openfeign远程调用
将服务注册到nacos注册表
依赖:注意nacos版本号与springboot版本号是否搭配,不搭配启动报错
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!--nacos依赖-->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
- <version>2021.0.1.0</version>
- </dependency>
- <!--nacos配置文件依赖,不在nacos配置的不需要引入-->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
- <version>2021.0.1.0</version>
- </dependency>
配置文件
- server:
- port: 8080
- spring:
- application:
- name: user
- cloud:
- nacos:
- discovery:
- server-addr: localhost:8848 #IP地址
写请求接口代码
- @GetMapping("/find")
- public String findUser(@RequestParam String name){
- return name;
- }
添加nacos与openfeign依赖:注意nacos版本号与springboot版本号是否搭配,不搭配启动报错
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!--远程调用依赖-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- <version>3.1.5</version>
- </dependency>
- <!--nacos依赖-->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
- <version>2021.0.1.0</version>
- </dependency>
- <!--高版本openfeign需要添加,否则报错-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-loadbalancer</artifactId>
- <version>3.1.3</version>
- </dependency>
配置文件
- server:
- port: 8081
- spring:
- application:
- name: open
- cloud:
- nacos:
- discovery:
- server-addr: localhost:8848 #IP地址
启动类加注解:@EnableFeignClients
- @SpringBootApplication
- @EnableFeignClients
- public class OpenFeignUserApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(OpenFeignUserApplication.class, args);
- }
-
- }
添加调用接口:user指调注册到nacos的服务
- package com.example.openfeignuser.openfeign;
-
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestParam;
-
- @FeignClient(value = "user")
- public interface UserClient {
- /**调用user服务的findUser接口*/
- @GetMapping("/user/find")
- String findUser(@RequestParam("name") String name);
- }
在需要调用的类注入接口进行调用
- package com.example.openfeignuser.service.impl;
-
- import com.example.openfeignuser.openfeign.UserClient;
- import com.example.openfeignuser.service.OpenFeignService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- @Service
- public class OpenFeignServiceImpl implements OpenFeignService {
- @Autowired
- private UserClient userClient;
-
- @Override
- public String findUser(String name) {
- return userClient.findUser(name);
- }
- }
不存在多个服务多个接口多调用不需要
后续更新
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。