SpringCloud Alibaba 整合 Nacos 和 Feign

avatar 2021年01月29日00:26:21 0 115 views

上文介绍了本地安装 nacos,猛戳此处直达

本文介绍 springcloud alibaba 整合 nacos 和 fegin 实现Rest风格基本的增删改查

这里一个个服务方系统和消费方系统来介绍,为了方便我们学习,我这里放在一个多模块项目里。

代码地址:https://github.com/saysky/nacos-spring-cloud-example

一、项目结构

 

开发之前注意先启动注册中心 Nacos 哦!

 

二、服务提供者代码

先贴一下父模块的 pom.xml 即最外层的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.liuyanzhao</groupId>
    <artifactId>nacos-spring-cloud-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>nacos-spring-cloud-example</name>

    <packaging>pom</packaging>


    <modules>
        <module>demo-provider-service</module>
        <module>demo-consumer-service</module>
    </modules>

</project>

 

1、然后是服务提供者的 pom.xml

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-provider-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-provider-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <fastjson.version>1.2.72</fastjson.version>
        <spring-cloud.version>Greenwich.SR5</spring-cloud.version>
        <spring-nacos.version>2.1.1.RELEASE</spring-nacos.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${spring-nacos.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

2、然后配置文件

application.yml

server:
  port: 8082
spring:
  application:
    name: demo-provider-service
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

 

3、DemoProviderApplication.java

package com.example.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoProviderApplication.class, args);
    }

}

 

4、User.java

package com.example.provider.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户对象
 *
 * @author 言曌
 * @date 2021/1/28 11:20 下午
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    /**
     * ID
     */
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String sex;
}

 

5、ProviderController.java

package com.example.provider.controller;

import com.alibaba.fastjson.JSON;
import com.example.provider.pojo.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 服务端接口
 * 这里主要是测试 增删改查几种请求类型
 * 备注:这里为了简单这里返回数据了,就不封装返回结构了
 *
 * @author 言曌
 * @date 2021/1/28 11:22 下午
 */
@RestController
public class ProviderController {

    /**
     * 这里就不创建数据库了
     * 通过内存对象操作,模拟数据库读写
     */
    public static List<User> userList = new ArrayList<>();

    static {
        userList.add(new User(1L, "熊熊", "女"));
        userList.add(new User(2L, "慈慈", "男"));
        userList.add(new User(3L, "瞾曌", "男"));
        userList.add(new User(4L, "肥肥", "女"));
    }

    /**
     * 模拟获取用户列表
     *
     * @return
     */
    @GetMapping("/user")
    public String getUserList() {
        return JSON.toJSONString(userList);
    }

    /**
     * 模拟根据用户ID查询用户
     *
     * @return
     */
    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable("id") Long id) {
        for (User user : userList) {
            if (Objects.equals(user.getId(), id)) {
                return JSON.toJSONString(user);
            }
        }
        return null;
    }


    /**
     * 模拟添加用户
     *
     * @return
     */
    @PostMapping("/user")
    public String addUser(@RequestBody User user) {
        userList.add(user);
        return "success";
    }


    /**
     * 模拟更新用户
     *
     * @return
     */
    @PutMapping("/user")
    public String updateUser(@RequestBody User user) {
        int index = 0;
        for (User u : userList) {
            if (Objects.equals(u.getId(), user.getId())) {
                userList.set(index, user);
                break;
            }
            index++;
        }
        return "success";
    }

    /**
     * 模拟更新用户
     *
     * @return
     */
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") Long id) {
        Iterator<User> it = userList.iterator();
        while (it.hasNext()) {
            User e = it.next();
            if (Objects.equals(id, e.getId())) {
                it.remove();
                break;
            }
        }
        return "success";
    }


}

 

三、服务消费者代码

1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-consumer-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-consumer-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR5</spring-cloud.version>
        <spring-nacos.version>2.1.1.RELEASE</spring-nacos.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${spring-nacos.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

2、application.yml

server:
  port: 8081
spring:
  application:
    name: demo-consumer-service
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

 

3、DemoConsumerApplication.java

package com.example.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author 言曌
 */
@SpringBootApplication
@EnableFeignClients
public class DemoConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoConsumerApplication.class, args);
    }

}

 

4、User.java

package com.example.consumer.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户对象
 * 这个类可以由服务方提供jar包,或者消费方根据服务方的接口文档自己定义类
 *
 * @author 言曌
 * @date 2021/1/28 11:20 下午
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    /**
     * ID
     */
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String sex;
}

 

5、DemoProvideService.java

package com.example.consumer.feign;

import com.example.consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;


/**
 * 这个 feign 接口一般由服务提供方提供jar
 * 或者消费方根据服务方的接口文档,自己写这个feign接口
 *
 * @author 言曌
 * @date 2021/1/28 11:42 下午
 */
@FeignClient("demo-provider-service")
public interface DemoProviderService {
    /**
     * 模拟获取用户列表
     *
     * @return
     */
    @GetMapping("/user")
    String getUserList();

    /**
     * 模拟根据用户ID查询用户
     *
     * @return
     */
    @GetMapping("/user/{id}")
    String getUserById(@PathVariable("id") Long id);


    /**
     * 模拟添加用户
     *
     * @return
     */
    @PostMapping("/user")
    String addUser(@RequestBody User user);


    /**
     * 模拟更新用户
     *
     * @return
     */
    @PutMapping("/user")
    String updateUser(@RequestBody User user);

    /**
     * 模拟更新用户
     *
     * @return
     */
    @DeleteMapping("/user/{id}")
    String deleteUser(@PathVariable("id") Long id);


}

 

6、ProviderController.java

package com.example.consumer.controller;

import com.example.consumer.feign.DemoProviderService;
import com.example.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 模拟消费方去调用服务方的接口
 *
 * @author 言曌
 * @date 2021/1/28 11:48 下午
 */
@RestController
public class ConsumerController {

    @Autowired
    private DemoProviderService demoProviderService;


    /**
     * 调用服务方获取用户列表
     *
     * @return
     */
    @GetMapping("/user")
    public String getUserList() {
        return demoProviderService.getUserList();
    }

    /**
     * 调用服务方根据用户ID查询用户
     *
     * @return
     */
    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable("id") Long id) {
        return demoProviderService.getUserById(id);
    }


    /**
     * 调用服务方添加用户
     *
     * @return
     */
    @PostMapping("/user")
    public String addUser(@RequestBody User user) {
        return demoProviderService.addUser(user);
    }


    /**
     * 调用服务方更新用户
     *
     * @return
     */
    @PutMapping("/user")
    public String updateUser(@RequestBody User user) {
        return demoProviderService.updateUser(user);
    }


    /**
     * 调用服务方更新用户
     *
     * @return
     */
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") Long id) {
        return demoProviderService.deleteUser(id);
    }


}

 

四、运行测试

先启动 Nacos

然后启动以上两个项目,服务提供者和消费者

看 Nacos 可视化页面,服务注册状态

2个服务都注册了,OK!

 

然后访问消费方的接口,使用 Postman 测试

1、测试根据id查询用户

 

2、测试添加用户

 

3、测试更新用户

 

4、测试删除用户

 

5、测试查询用户列表

 

可见服务消费方能正常调用服务提供者,完美!!!

下篇文章我们介绍 Sentinel,将 Sentinel 引入项目,实现服务熔断降级

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
可以匿名评论或者登录后台评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0