学无先后,达者为师

网站首页 编程语言 正文

spring cloud alibaba nacos搭建最小可运行微服务

作者:Rewloc 更新时间: 2022-05-11 编程语言

一、环境

开发工具:IntelliJ Idea
JDK 1.8
Spring boot 2.3.12.RELEASE
spring cloud Alibaba 2.2.7.RELEASE
openfeign 2.2.9.RELEASE

二、程序目录

可以通过开发工具中的maven、spring initializr等进行项目创建。内容包括:父工程、两个子工程。结构如下图:
在这里插入图片描述

①父工程,该工程仅是pom工程,向子工程提供pom的继承。
②子工程,用于两个服务之间的调用

  • 工程说明:
  • order服务通过restTemplate和openfeign两种方式分别调用stock服务中的reduct接口

三、配置文件

  • 3.1 父POM文件

<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.0modelVersion>

    <groupId>com.jwsswgroupId>
    <artifactId>microserviceartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>microservicename>
    <description>microservicedescription>
    <packaging>pompackaging>
    
    <modules>
        <module>ordermodule>
        <module>stockmodule>
    modules>
    
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.12.RELEASEversion>
        <relativePath/> 
    parent>
    
    <properties>
        <java.version>8java.version>
        <spring.cloud.version>Hoxton.SR12spring.cloud.version>
        <alibaba.cloud.version>2.2.7.RELEASEalibaba.cloud.version>
    properties>
    
    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring.cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                <version>${alibaba.cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>
  • 3.2 子工程POM,除artifactId外两个子工程配置一致

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <parent>
        <artifactId>microserviceartifactId>
        <groupId>com.jwsswgroupId>
        <version>0.0.1-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>orderartifactId>

    
    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    
    <dependencies>
    dependencies>
project>
  • 3.3 application.yml配置文件,除application.name外两个子工程配置一致
server:
  port: 8011

# spring 相关配置
spring:
  application:
    name: order-server # 服务名称
  cloud:
    # nacos客户端配置
    nacos:
      discovery:
        server-addr: 192.168.0.182:8848 # nacos服务地址

# feign配置
feign:
  # 是否开启服务降级,默认不开启,true表示开启
  hystrix:
    enabled: true

四、程序代码

4.1 Order子工程的相关代码
  • 4.1.1 启动类OrderApplication
package com.jwssw.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * 类描述:启动类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/19 10:42
 * @since JDK 8
 */
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    /**
     * 方法描述: 启动类入口
     *
     * @param args 参数
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 13:50
     */
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }


    /**
     * 方法描述: 装载restTemplate bean对象
     *
     * @param builder 配置类
     * @return {@link RestTemplate}
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 13:51
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
  • 4.1.2 控制类OrderController
package com.jwssw.order;

import com.jwssw.order.service.OrderService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 类描述:对外提供服务类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/19 10:43
 * @since JDK 8
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    /** restTemplate远程调用对象 */
    private final RestTemplate restTemplate;
    /** openfeign远程调用对象 */
    private final OrderService orderService;

    /**
     * 构造方法注入
     */
    public OrderController(RestTemplate restTemplate,
                           @Qualifier("com.jwssw.order.service.OrderService") OrderService orderService) {
        this.restTemplate = restTemplate;
        this.orderService = orderService;
    }

    /**
     * 方法描述: 采用restTemplate方式远程调用
     *
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:11
     */
    @RequestMapping("/add")
    public String add() {
        // 远程调用
        String str = restTemplate.getForObject("http://stock-server/stock/reduct", String.class);
        // 返回结果
        return "Hello World " + str;
    }


    /**
     * 方法描述: 采用openfeign方式远程调用
     *
     * @return {@link String}
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:12
     */
    @RequestMapping("/feignAdd")
    public String feignAdd() {
        // openfeign调用远程接口
        String str = orderService.reduct();
        // 返回结果
        return "feign调用:" + str;
    }
}
  • 4.1.3 openfeign接口类OrderService
package com.jwssw.order.service;

import com.jwssw.order.service.impl.OrderServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 类描述:openfeign远程调用接口类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/24 09:53
 * @since JDK 8
 */
@FeignClient(name = "stock-server", fallback = OrderServiceImpl.class)
public interface OrderService {
    /**
     * 方法描述: 调用stock服务的reduct接口的方法
     *
     * @return {@link String}
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:23
     */
    @GetMapping("/stock/reduct")
    String reduct();
}
  • 4.1.4 回调类OrderServiceImpl
package com.jwssw.order.service.impl;

import com.jwssw.order.service.OrderService;
import org.springframework.stereotype.Component;

/**
 * 类描述:openfeign远程调用失败的回调类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/24 09:54
 * @since JDK 8
 */
@Component
public class OrderServiceImpl implements OrderService {
    /**
     * 方法描述: 调用失败后的回调方法
     *
     * @return {@link String}
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:23
     */
    @Override
    public String reduct() {
        return "库存服务不可达";
    }
}
4.2 stock子工程的相关代码
  • 4.2.1 启动类StockApplication
package com.jwssw.stock;

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

/**
 * 类描述:stock项目启动类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/19 10:52
 * @since JDK 8
 */
@SpringBootApplication
public class StockApplication {
    /**
     * 方法描述: stock服务启动入口
     *
     * @param args 参数
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:27
     */
    public static void main(String[] args) {
        SpringApplication.run(StockApplication.class, args);
    }
}
  • 4.2.2 对外提供服务类StockController
package com.jwssw.stock;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类描述:对外提供服务类
 *
 * @author 鲁浩鹏 Lu Haopeng
 * @version 1.0
 * @email Lu Haopeng
 * @date 2022/3/19 10:46
 * @since JDK 8
 */
@RestController
@RequestMapping("/stock")
public class StockController {
    
    /** 获取配置文件中的端口号 */
    @Value("${server.port}")
    private String port;

    /**
     * 方法描述: 对外提供的方法
     *
     * @return {@link String}
     * @author 鲁浩鹏 Lu Haopeng
     * @date 2022/3/25 14:29
     */
    @RequestMapping("/reduct")
    public String reduct() {
        System.out.println("扣减库存成功");
        return "扣减库存" + port;
    }
}

五、总结

以上内容主要给予spring cloud alibaba的最小可运行的微服务Demo工程,如果你在实际项目中尚未微服务,不妨可以采用本文上述方式在实际项目中推行一下。

原文链接:https://blog.csdn.net/lhp3000/article/details/123735389

栏目分类
最近更新