springboot+duubo+nacos搭建

31
五月
2021

一、nacos server下载安装

1.下载

https://github.com/alibaba/nacos/tags

2.安装 

我就在windows上演示一下单机版。这里下载的.zip文件

 cmd startup.cmd -m standalone

访问界面:http://localhost:8848/nacos

默认账号密码都是nacos

此时说明启动成功 

二、nacos作为注册中心的使用

把整个demo项目一起贴出来

父项目pom

<?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.sid</groupId>
    <artifactId>springboot-dubbo-sentinel-nacos</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>business</module>
        <module>storage</module>
        <module>order</module>
        <module>account</module>
        <module>api</module>
    </modules>

    <properties>
        <java.version>1.8</java.version>
        <spring-boot.version>2.1.9.RELEASE</spring-boot.version>
        <dubbo.version>2.7.3</dubbo.version>
    </properties>

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

            <!-- Apache Dubbo  -->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-dependencies-bom</artifactId>
                <version>${dubbo.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- Dubbo Spring Boot Starter -->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-spring-boot-starter</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo</artifactId>
                <version>${dubbo.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>log4j</groupId>
                        <artifactId>log4j</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>apache.snapshots.https</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

api项目

就是RPC调用的接口

pom

<?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>springboot-dubbo-sentinel-nacos</artifactId>
        <groupId>com.sid</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>api</artifactId>

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

</project>

 

package com.sid.rpc.service.service;

public interface AccountServiceApi {

    String debit(String userId, Double money);

    String insert(String userId, Double money);

    String setMoney(String userId, Double money);

    String deleteAccount(String userId);

}
package com.sid.rpc.service.service;

import com.sid.rpc.service.model.Order;

public interface OrderServiceApi {
    Order create(String userId, String commodityCode, Integer orderCount);
}

 

package com.sid.rpc.service.service;

public interface StorageServiceApi {

    String deduct(String commodityCode, int count);
}
package com.sid.rpc.service.model;

import java.io.Serializable;

public class Account implements Serializable {
    private String userId;

    private Double money;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }
}

 

package com.sid.rpc.service.model;


import java.io.Serializable;

public class Order implements Serializable {
    private Long orderId;

    private String userId;

    private String commodityCode;

    private Integer orderCount;

    private Double orderMoney;

    private String msg;


    public Long getOrderId() {
        return orderId;
    }

    public void setOrderId(Long orderId) {
        this.orderId = orderId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }

    public String getCommodityCode() {
        return commodityCode;
    }

    public void setCommodityCode(String commodityCode) {
        this.commodityCode = commodityCode == null ? null : commodityCode.trim();
    }

    public Integer getOrderCount() {
        return orderCount;
    }

    public void setOrderCount(Integer orderCount) {
        this.orderCount = orderCount;
    }

    public Double getOrderMoney() {
        return orderMoney;
    }

    public void setOrderMoney(Double orderMoney) {
        this.orderMoney = orderMoney;
    }


    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

account项目

 pom

<?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>springboot-dubbo-sentinel-nacos</artifactId>
        <groupId>com.sid</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>account</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <!-- 排除自带的logback依赖 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
        <!-- Dubbo -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>

        <!-- Dubbo Registry Nacos -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-registry-nacos</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.sid</groupId>
            <artifactId>api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>apache.snapshots.https</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
<!--                <version>2.0.1.RELEASE</version>-->
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <!-- 这样就不用再generatorConfig.xml里面配置本地的mysql-connector-java位置了-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

目录

application.yml

dubbo相关参数:可以在DubboConfigurationProperties类中查看

server:
  port: 8084

###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如订单服务)
spring:
  application:
    name: app-account
  datasource:
    url: jdbc:mysql://localhost:3306/test-account
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

# nacos address
nacos:
  server-address: localhost
  port: 8848

# Dubbo Application
dubbo:
  # Dubbo Protocol
  protocol:
    name: dubbo
    ## Random port
    port: -1
  ## Dubbo Registry
  registry:
    address: nacos://${nacos.server-address}:${nacos.port}
  application:
    name: ${spring.application.name}
  scan:
    base-packages: com.sid.api.service

## 该配置节点为独立的节点,不是在在spring的节点下
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.sid.model  # 注意:对应实体类的路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台打印sql

启动类

package com.sid;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.sid.com.mapper")
@EnableDubbo
public class AccountApp {
    public static void main(String[] args) {
        SpringApplication.run(AccountApp.class, args);
    }
}

 RPCimpl

package com.sid.rpc.service;

import com.sid.rpc.service.service.AccountServiceApi;
import com.sid.service.AccountService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;


@Service(group = "account-provider", version = "1.0.0")
public class AccountServiceRpcImpl implements AccountServiceApi {

    @Autowired
    private AccountService accountService;

    /**
     * 扣钱
     * */
    @Override
    public String debit(String userId, Double money) {
        return accountService.debit(userId,money);
    }

    @Override
    public String insert(String userId, Double money){
        return accountService.insert(userId,money);
    }

    @Override
    public String setMoney(String userId, Double money){
        return accountService.setMoney(userId,money);
    }

    @Override
    public String deleteAccount(String userId){
        return accountService.deleteAccount(userId);
    }

}

业务逻辑service

package com.sid.service;

import com.sid.mapper.AccountMapper;
import com.sid.model.Account;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AccountServiceImpl implements AccountService{
    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional
    public String debit(String userId, Double money) {
        Account account = accountMapper.selectByPrimaryKey(userId);
        Double money1 = account.getMoney();
        account.setMoney(money1-money);
        int i = accountMapper.updateByPrimaryKey(account);
        if(i == 1){
            return "success";
        }
        return "fail";
    }

    @Override
    @Transactional
    public String insert(String userId, Double money){
        Account account = new Account();
        account.setUserId(userId);
        account.setMoney(money);
        int i = accountMapper.insert(account);
        if(i == 1){
            return "success";
        }
        return "fail";
    }

    @Override
    @Transactional
    public String setMoney(String userId, Double money){
        Account account = new Account();
        account.setUserId(userId);
        account.setMoney(money);
        int i = accountMapper.updateByPrimaryKey(account);
        if(i == 1){
            return "success";
        }
        return "fail";
    }

    @Override
    @Transactional
    public String deleteAccount(String userId){
        int i = accountMapper.deleteByPrimaryKey(userId);
        if(i == 1){
            return "success";
        }
        return "fail";
    }
}

 mapper和mapping和model是用mybatis的插件直接生成的

storage项目

pom

<?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>springboot-dubbo-sentinel-nacos</artifactId>
        <groupId>com.sid</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>storage</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <!-- 排除自带的logback依赖 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
        <!-- Dubbo -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>

        <!-- Dubbo Registry Nacos -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-registry-nacos</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.sid</groupId>
            <artifactId>api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>apache.snapshots.https</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.1.RELEASE</version>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <!-- 这样就不用再generatorConfig.xml里面配置本地的mysql-connector-java位置了-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

项目目录

启动类

package com.sid;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.sid.mapper")
@EnableDubbo
public class StorageApp {
    public static void main(String[] args) {
        SpringApplication.run(StorageApp.class, args);
    }
}

 application.yml

server:
  port: 8083

###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如订单服务)
spring:
  application:
    name: app-storage
  datasource:
    url: jdbc:mysql://localhost:3306/test-storage
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

# nacos address
nacos:
  server-address: localhost
  port: 8848

# Dubbo Application
dubbo:
  # Dubbo Protocol
  protocol:
    name: dubbo
    ## Random port
    port: -1
  ## Dubbo Registry
  registry:
    address: nacos://${nacos.server-address}:${nacos.port}
  application:
    name: ${spring.application.name}
  scan:
    base-packages: com.sid.api.service

## 该配置节点为独立的节点,不是在在spring的节点下
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.sid.model  # 注意:对应实体类的路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台打印sql

RPC实现类

package com.sid.rpc.service;


import com.sid.rpc.service.service.StorageServiceApi;
import com.sid.service.StorageService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service(group = "storage-provider", version = "1.0.0")
public class StorageServiceRpcImpl implements StorageServiceApi {

    @Autowired
    private StorageService StorageService;

    /**
     * 商品扣库存
     * */
    @Override
    public String deduct(String commodityCode, int count) {

        return StorageService.deduct(commodityCode,count);
    }
}

 业务service

package com.sid.service;

import com.sid.mapper.StorageMapper;
import com.sid.model.Storage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageMapper storageMapper;

    /**
     * 商品扣库存
     * */
    @Override
    @Transactional
    public String deduct(String commodityCode, int count) {
        Storage storage = storageMapper.selectByPrimaryKey(commodityCode);
        Integer storageCount = storage.getStorageCount();
        storage.setStorageCount(storageCount - count);
        int i = storageMapper.updateByPrimaryKey(storage);
        //int ii = 1/0;
        if(i == 1){
            return "success";
        }
        return "fail";
    }
}

order项目

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>springboot-dubbo-sentinel-nacos</artifactId>
        <groupId>com.sid</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <!--            <exclusions>-->
            <!--                &lt;!&ndash; 排除自带的logback依赖 &ndash;&gt;-->
            <!--                <exclusion>-->
            <!--                    <groupId>org.springframework.boot</groupId>-->
            <!--                    <artifactId>spring-boot-starter-logging</artifactId>-->
            <!--                </exclusion>-->
            <!--            </exclusions>-->
        </dependency>
        <!--        <dependency>-->
        <!--            <groupId>org.springframework.boot</groupId>-->
        <!--            <artifactId>spring-boot-starter-log4j2</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>
        <!-- Dubbo -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>

        <!-- Dubbo Registry Nacos -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-registry-nacos</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.sid</groupId>
            <artifactId>api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>apache.snapshots.https</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <!-- 这样就不用再generatorConfig.xml里面配置本地的mysql-connector-java位置了-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

 目录

application.yml

server:
  port: 8082

###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如订单服务)
spring:
  application:
    name: app-order
  datasource:
    url: jdbc:mysql://localhost:3306/test-order
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

# nacos address
nacos:
  server-address: localhost
  port: 8848

# Dubbo Application
dubbo:
  # Dubbo Protocol
  protocol:
    name: dubbo
    ## Random port
    port: -1
  ## Dubbo Registry
  registry:
    address: nacos://${nacos.server-address}:${nacos.port}
  application:
    name: ${spring.application.name}
  scan:
    base-packages: com.sid.api.service

## 该配置节点为独立的节点,不是在在spring的节点下
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.sid.model  # 注意:对应实体类的路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台打印sql


# log config
logging:
  config: classpath:logback-spring.xml

启动类

package com.sid;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@MapperScan("com.sid.mapper")
@SpringBootApplication
@EnableDubbo
public class OrderApp {
    public static void main(String[] args) {
        SpringApplication.run(OrderApp.class, args);
    }

}

 RPC服务实现

package com.sid.rpc.service;


import com.sid.rpc.service.model.Order;
import com.sid.rpc.service.service.OrderServiceApi;
import com.sid.service.OrderService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service(group = "order-provider", version = "1.0.0")
public class OrderServiceRpcImpl implements OrderServiceApi {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @Override
    public Order create(String userId, String commodityCode, Integer orderCount) {
        com.sid.model.Order order = orderService.create(userId, commodityCode, orderCount);
        Order o = new Order();
        o.setOrderCount(order.getOrderCount());
        o.setCommodityCode(order.getCommodityCode());
        o.setUserId(o.getUserId());
        o.setOrderMoney(order.getOrderMoney());
        o.setOrderId(order.getOrderId());
        o.setMsg(order.getMsg());
        return o;
    }
}

业务service中RPC调用account服务

package com.sid.service;

import com.sid.mapper.OrderMapper;
import com.sid.model.Order;
import com.sid.rpc.service.service.AccountServiceApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl implements OrderService{

    @Reference(check = false,group = "account-provider", version = "1.0.0")
    private AccountServiceApi accountServiceApi;

    @Resource
    private OrderMapper orderMapper;

    /**
     * 创建订单
     */
    @Override
    @Transactional
    public Order create(String userId, String commodityCode, Integer orderCount) {
        Double orderMoney = Double.valueOf(orderCount);
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setOrderCount(orderCount);
        order.setOrderMoney(orderMoney);

        orderMapper.insertSelective(order);

        /**
         * 这里的RPC调用是同步的
         * todo 需要写个异步的例子  这个可能需要用dubbo来写哦  feign都是同步个嘛
         * */
        String accountDebitResult = accountServiceApi.debit(userId, orderMoney);

        if (!accountDebitResult.equals("success")) {
            System.out.println("result account service :"+accountDebitResult);
            throw new RuntimeException("OrderService create method rpc request accountService debit fail. accountDebitResult:"+accountDebitResult);
        }

        order.setMsg("success");
        return order;
    }
}

business项目

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>springboot-dubbo-sentinel-nacos</artifactId>
        <groupId>com.sid</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>business</artifactId>

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
            <scope>runtime</scope>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <dependency>
            <groupId>com.sid</groupId>
            <artifactId>api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 排除自带的logback依赖 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</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>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>

        <!-- Dubbo Registry Nacos -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-registry-nacos</artifactId>
            <version>2.7.3</version>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>apache.snapshots.https</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

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

            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <!-- 这样就不用再generatorConfig.xml里面配置本地的mysql-connector-java位置了-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

项目目录

application.yml

server:
  port: 8085


###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如订单服务)
spring:
  application:
    name: app-business
  datasource:
    url: jdbc:mysql://localhost:3306/test-business
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
# nacos address
nacos:
  server-address: localhost
  port: 8848

# Dubbo Application
dubbo:
  # Dubbo Protocol
  protocol:
    name: dubbo
    ## Random port
    port: -1
  ## Dubbo Registry
  registry:
    address: nacos://${nacos.server-address}:${nacos.port}
  application:
    name: ${spring.application.name}
  scan:
    base-packages: com.sid.api.service

## 该配置节点为独立的节点,不是在在spring的节点下
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.sid.model  # 注意:对应实体类的路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台打印sql

# log config
logging:
  config: classpath:logback-spring.xml

启动类

package com.sid;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
@EnableDubbo
@MapperScan("com.sid.mapper")
public class BusinessApp {
    public static void main(String[] args) {
        SpringApplication.run(BusinessApp.class, args);
    }

}

业务service,RPC调用order服务和storage服务

package com.sid.service;

import com.sid.mapper.BusinessMapper;
import com.sid.model.Business;
import com.sid.rpc.service.model.Order;
import com.sid.rpc.service.service.OrderServiceApi;
import com.sid.rpc.service.service.StorageServiceApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BusinessServiceImpl implements BusinessService{

    @Reference(check = false,group = "order-provider", version = "1.0.0")
    OrderServiceApi orderServiceApi;

    @Reference(check = false,group = "storage-provider", version = "1.0.0")
    StorageServiceApi storageServiceApi;

    @Resource
    BusinessMapper businessMapper;

    /**
     * 采购
     */
    @Transactional
    @Override
    public void purchase(String userId, String commodityCode, int orderCount) {

        Business b = new Business();
        b.setUserId(userId);
        b.setCommodityCode(commodityCode);
        b.setOrderCount(orderCount);

        int i = businessMapper.insertSelective(b);

        String storageDeductResult = storageServiceApi.deduct(commodityCode, orderCount);
        System.out.println(storageDeductResult);

        Order order = orderServiceApi.create(userId, commodityCode, orderCount);

        String orderCreateResult = order.getMsg();


        if(!storageDeductResult.equals("success") || !orderCreateResult.equals("success")){
            System.out.println("resutl storage service :"+storageDeductResult);

            System.out.println("resutl order service :"+orderCreateResult);

            throw new RuntimeException("BusinessServiceImpl purchase fail");
        }

    }

    @Override
    public Business selectByBusiness(Long businessId){
        Business business = businessMapper.selectByPrimaryKey(businessId);
        return business;
    }

    @Override
    public List<Business> selectByCommodityCode(String CommodityCode){
        List<Business> list = businessMapper.selectByCommodityCode(CommodityCode);
        return list;
    }

    @Override
    @Transactional
    public String updateOrderCountByBusinessId(Long businessId, Integer orderCount){
        Business business = new Business();
        business.setBusinessId(businessId);
        business.setOrderCount(orderCount);
        int i = businessMapper.updateByPrimaryKeySelective(business);
        if(i == 1){
            return "success";
        }
        return "fail";
    }

    @Override
    @Transactional
    public String delete(Long businessId){
        int i = businessMapper.deleteByPrimaryKey(businessId);
        if(i == 1){
            return "success";
        }
        return "fail";
    }


}

 三、nacos作为配置中心使用

nacos open api 

以上面那个business项目为例子,在此基础之上做修改

pom.xml中加入一个依赖

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.3</version>
        </dependency>

application.yml加入

nacos:
  server-address: localhost
  port: 8848
  config:
    server-addr: ${nacos.server-address}:${nacos.port}

nacos配置类

package com.sid.config;

import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.context.annotation.Configuration;

//@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "localhost:8848"))
@NacosPropertySource(dataId = "app-business", type = ConfigType.PROPERTIES, autoRefreshed = true)
@Configuration
public class NacosConfig {

    @NacosValue(value = "${business.testConfig}", autoRefreshed = true)
    private String businessTestConfig;

    public String getBusinessTestConfig() {
        return businessTestConfig;
    }

    public void setBusinessTestConfig(String businessTestConfig) {
        this.businessTestConfig = businessTestConfig;
    }
}

使用nacos中的配置

package com.sid.controller;

//import com.sid.config.NacosConfig;
import com.sid.config.NacosConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//@RefreshScope
@RestController
public class BusinessController {

    @Autowired
    NacosConfig nacosConfig;

//    @Value(value = "${business.testConfig:1}")
//    private String businessTestConfig;

    @RequestMapping(value = "business/config",method = RequestMethod.GET)
    public String config() {
//        return businessTestConfig;
        return nacosConfig.getBusinessTestConfig();
    }
}

在nacos管理界面创建配置文件

参数说明

Data Id

Data Id的默认值为${nacos.config.prefix}-${spring.profile.active}.${nacos.config.file-extension}

nacos.config.prefix的默认值为${spring.application.name}

nacos.config.file-extension的默认值为properties

当spring.profiles.active未配置时,则匹配${spring.application.name}.properties

若设置了spring.profiles.active而Nacos中存在${spring.application.name}.properties时,若还存在${spring.application.name}-${spring.profiles.active}.properties,则默认匹配后者,若不存在,则会自动匹配前者

由于Nacos建议且默认用spring.application.name作为Data Id的前缀

Group

这是一个很灵活的配置项,并没有固定的规定,可以用作多环境、多模块、多版本之间区分配置

Namespace

推荐使用命名空间来区分不同环境的配置,因为使用profilesgroup会是不同环境的配置展示到一个页面,而Nacos控制台对不同的Namespace做了Tab栏分组展示

如果需要不同环境用不同的配置,则创建一个命名空间比如叫dev

在该命名空间下创建配置文件app-business

 

然后在项目的yml中配上命名空间的ID

# nacos address
nacos:
  server-address: localhost
  port: 8848
  config:
    server-addr: ${nacos.server-address}:${nacos.port}
    namespace: 48acfc39-0299-4c3e-af1a-ecb8b24ad524  # 命名空间ID 不是命名空间名称 以此区分dev sit pro环境

 这样读到的就是dev下面的app-business文件的配置了

 

TAG

网友评论

共有访客发表了评论
请登录后再发布评论,和谐社会,请文明发言,谢谢合作! 立即登录 注册会员