SpringCloud整合Alibaba环境搭建

x33g5p2x  于2021-09-19 转载在 Spring  
字(18.8k)|赞(0)|评价(0)|浏览(677)

准备工作

环境要求

JDK 1.8.+、Maven 3.6.3、springboot 2.2.5、springcloud Hoxton+、springcloud alibaba 2.2.1.RELEASE

整合思路

服务注册中心  	nacos
统一配置中心  	nacos
服务熔断组件  	sentinel
服务间通信组件  openfeign + ribbon 
服务网关组件    gateway

启动服务

在上面整个思路里面可以看到我们需要nacossentinel。所以在开始搭建之前我们先启动这两个服务。如下图所示

搭建步骤

初始化parent

1.新建parent
microservices

microservices作为项目空间用作隔离其他的项目,仅仅是一个EmptyProject.

springcloud_alibaba_parent

我们在项目空间中新建一个Module – springcloud_alibaba_parent作为我们微服务框架的父项目,用来管理依赖及其版本

2.配置parent
maven

首先我们更改maven的路径为本地(一般新建项目都需要检查),如下图所示:

Log Support

Other Settings中找到Log Support,修改其Frameworkslf4j。如下图所示:

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.christy</groupId>
    <artifactId>springcloud_alibaba_parent</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--继承springboot父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

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

        <spring.cloud.version>Hoxton.SR6</spring.cloud.version>
        <spring.cloud.alibaba.version>2.2.1.RELEASE</spring.cloud.alibaba.version>
    </properties>

    <!--维护依赖-->
    <dependencyManagement>
        <dependencies>
            <!--维护springcloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--维护springcloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>

    </dependencyManagement>
</project>

初始化common

1.新建Module

springcloud_alibaba_common作为公共依赖(暂时不做处理),主要存放后期的entity或者utils。我们新建一个Module,父项目选择上面的parent。如下图所示:

初始化users

springcloud_alibaba_usersspringcloud_alibaba_products作为本次微服务框架搭建的两个主要示例,主要展示在users中调用product中的方法来展示微服务间的调用。首先我们来看下springcloud_alibaba_users的搭建

1.新建Module

2.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_users</artifactId>

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

    <dependencies>
        <!-- spring-boot-starter-web -->
        <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>
        </dependency>
    </dependencies>
</project>
3.application.properties
server.port=8881
spring.application.name=USERS

# 注册到nacos
spring.cloud.nacos.server-addr=192.168.8.190:8848
4.UserApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/** * @Author Christy * @Date 2021/8/27 9:49 **/
@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
    public static void main(String[] args){
        SpringApplication.run(UserApplication.class, args);
    }
}
5.启动

我们启动该模块,然后在nacos的服务管理列表中能够看到该服务,则说明我们的springcloud_alibaba_users初始搭建是没有问题的。

初始化products

1.新建Module

2.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_products</artifactId>

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

    <dependencies>
        <!-- spring-boot-starter-web -->
        <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>
        </dependency>
    </dependencies>
</project>
3.application.properties
server.port=8882
spring.application.name=PRODUCTS

# 注册到nacos
spring.cloud.nacos.server-addr=192.168.8.190:8848
4.ProductApplicatioon.java
package com.christy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/** * @Author Christy * @Date 2021/8/27 9:56 **/
@SpringBootApplication
@EnableDiscoveryClient
public class ProductApplication {
    public static void main(String[] args){
        SpringApplication.run(ProductApplication.class, args);
    }
}
5.启动

我们启动该模块,然后在nacos的服务管理列表中能够看到该服务,则说明我们的springcloud_alibaba_products初始搭建是没有问题的。

服务间调用

上面我们的USERSPRODUCTS两个服务都已经启动成功了并且成功注册到了nacos,下面我们就要实现USERS调用PRODUCTS中的方法来实现微服务间的调用。

PRODUCTS

首先针对PRODUCTS,我们针对其ProductController实现如下方法:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * @Author Christy * @Date 2021/8/27 10:03 **/
@RestController
@RequestMapping("product")
public class ProductController {

    private static final Logger log = LoggerFactory.getLogger(ProductController.class);
    @Value("${server.port}")
    private int port;

     @GetMapping("port")
    public String product(){
        log.info("hello product!");
        return  "hello product! this port is: "+port;
    }
}
USERS

下面我们就要实现如何在USERS中调用PRODUCTS中的/product/port。在学习springcloud的时候我们知道通过ribbon+restTemplate的方式可以实现微服务间的通信。我们首先看下该种方法下的通信实现

ribbon+restTemplate
1.BeansConfig

我们在USERS中的config包下新建BeansConfig,在里面将RestTemplate交给Spring管理。通过ribbon的注解@LoadBalance实现负载均衡。代码如下:

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/** * @Author Christy * @Date 2021/8/27 10:09 **/
@Configuration
public class BeansConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
2.UserController

UserController中我们在invoke方法中通过RestTemplate调用PRODUCTS中的方法。代码如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/** * @Author Christy * @Date 2021/8/27 10:14 **/
@RestController
@RequestMapping("user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("invoke")
    public String invokeProduct() {
        log.info("Hello users!");
        String result = restTemplate.getForObject("http://PRODUCTS/product/port", String.class);
        log.info("result is {}", result);
        return result;
    }
}
3.测试

重新启动USERSPRODUCTS,在浏览器中访问http://localhost:8881/user/invoke。结果如下图所示:

我们说这种方式不好:他将路径写死在了代码中,不利于维护。所以后来我们讲到了OpenFeign

OpenFeign

我们来修改下USERS利用OpenFeign实现微服务间的通信。想要使用OpenFeign必须先引入相关依赖

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_users</artifactId>

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

    <dependencies>
        <!-- spring-boot-starter-web -->
        <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>
        </dependency>

        <!-- OpenFeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
</project>
2.UserApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/** * @Author Christy * @Date 2021/8/27 9:49 **/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients     //开启OpenFeign调用
public class UserApplication {
    public static void main(String[] args){
        SpringApplication.run(UserApplication.class, args);
    }
}
3.ProductClient.java

我们在USERS中的feignclients包中新建ProductClient.java。内容如下:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
/** * @Author Christy * @Date 2021/8/27 10:37 **/
@FeignClient("PRODUCTS")
public interface ProductClient {

    @RequestMapping("/product/port")
    String product();
}
4.UserControlller.java
import com.christy.feignclients.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/** * @Author Christy * @Date 2021/8/27 10:14 **/
@RestController
@RequestMapping("user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    /*@Autowired private RestTemplate restTemplate;*/

    @Autowired
    ProductClient productClient;

    @RequestMapping("invoke")
    public String invokeProduct() {
        log.info("Hello users!");
        /*String result = restTemplate.getForObject("http://PRODUCTS/product/port", String.class);*/
        String result = productClient.product();
        log.info("result is {}", result);
        return result;
    }
}
5.测试

重新启动USERS,在浏览器中访问http://localhost:8881/user/invoke。结果如下图所示:

集成Sentinel

这里我们以USERS服务为例集成Sentinel。

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_users</artifactId>

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

    <dependencies>
        <!-- spring-boot-starter-web -->
        <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>
        </dependency>

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

        <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
    </dependencies>
</project>
2.application.properties
server.port=8881
spring.application.name=USERS

# 注册到nacos
spring.cloud.nacos.server-addr=192.168.8.190:8848

# 与sentinel DashBoard建立通信
spring.cloud.sentinel.enabled=true
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.transport.port=8719
spring.cloud.sentinel.transport.dashboard=192.168.8.186:8999
# 设置发送心跳到DashBoard的主机地址
spring.cloud.sentinel.transport.clientIp=192.168.8.139
3.启动

我们重新启动USERS服务,然后在Sentinel DashBoard中找到该服务。如下图所示:

4.测试

我们在流控规则中对服务/user/invoke新增一条流控规则,如下图所示:

然后我们在浏览器中访问http://localhost:8881/user/invoke,当超过我们设置的单机阈值服务就会被熔断。如下图所示:

初始化Gateway

springcloud_alibaba_gateway作为我们的网关组件,作为请求的统一入口,在微服务框架中是必不可少的。

1.新建Module

2.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_gateway</artifactId>

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

    <dependencies>
        <!-- gateway -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!-- nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

</project>
3.GatewayApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/** * @Author Christy * @Date 2021/8/27 11:08 **/
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args){
        SpringApplication.run(GatewayApplication.class, args);
    }
}
4.application.yml
server:
  port: 8883

spring:
  application:
    name: GATEWAY

  cloud:
    nacos:
      server-addr: 192.168.8.190:8848

    gateway:
      routes:
        - id: users_route
          uri: lb://USERS
          predicates:
            - Path=/user/invoke

        - id: product_route
          uri: lb://PRODUCTS
          predicates:
            - Path=/product/port
5.启动

启动GATEWAY服务,如果能在nacos中看到看到就说明我们搭建成功了。如下图所示:

6.测试

我们在浏览器中访问http://localhost:8883/user/invokehttp://localhost:8883/product/port,都能得到如下图所示的结果:

远端拉取配置文件

我们之前说过如何使用nacos从远端拉取配置文件。实际上微服务中的所有服务的配置文件都可以放到远端。这里我们使用USERS举例回忆一下整个过程

1.新建命名空间

我们在nacos的管理界面选择命名空间->新建命名空间,按照下图所示新增一个命名空间

然后回到配置管理->配置列表,在配置列表中切换到我们上面新增的命名空间microservices

2.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_alibaba_parent</artifactId>
        <groupId>com.christy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_alibaba_users</artifactId>

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

    <dependencies>
        <!-- spring-boot-starter-web -->
        <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>
        </dependency>

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

        <!-- sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <!-- nacos config client -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
    </dependencies>
</project>
3.user-prod.properties

在配置列表中点击右上角的+,新增配置user-prod.properties,点击发布。内容如下:

4.bootstrap.properties
# 告诉config server地址
spring.cloud.nacos.config.server-addr=192.168.8.190:8848

# 告诉从哪个命名空间获取配置
spring.cloud.nacos.config.namespace=6feacc5a-0f14-47de-8157-72d139dd58ba
# 告诉从哪个组进行配置获取
spring.cloud.nacos.config.group=USER

# 第一种获取配置文件方式 dataId = name + file-extension
# 从这个组中拉取那个配置文件
spring.cloud.nacos.config.name=user-prod
# 拉取这个配置那个后缀的配置文件
spring.cloud.nacos.config.file-extension=properties

# 第二种获取配置文件方式 dataId = prefix + env + file-extension
# spring.cloud.nacos.config.prefix=user
# spring.profiles.active=prod
# spring.cloud.nacos.config.file-extension=properties
5.启动

重启USERS服务,仔细观察控制台,可以发现服务已经从远端成功拉取到了配置文件。如下图所示:

此时我们在浏览器中访问http://localhost:8883/user/invoke,服务也是正常的。控制台也正常输出了。如下图所示:

微服务的其他模块也可按照上面步骤将配置文件配置在远端,这里就不一一演示了。

使用SpringCloud与Alibaba整合搭建微服务初始框架就到这里了。继续加油ヾ(◍°∇°◍)ノ゙

相关文章