springboot+duubo+nacos build

1, nacos server download and installation

1. Download

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

2. Installation

I'll demonstrate the stand-alone version on windows. Download it here zip file

 cmd startup.cmd -m standalone

Access interface: http://localhost:8848/nacos

The default account password is nacos

At this time, it indicates that the startup is successful

2, Use of nacos as a registry

Post the whole demo project together

Parent item 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 project

The RPC interface is called

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 Project

 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>
                <!-- Exclude self-contained logback rely on -->
                <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 of druid Database connection pool -->
        <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 Automatic code generation plug-in -->
            <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>
                    <!-- So you don't have to generatorConfig.xml Local configuration inside mysql-connector-java Location-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

catalogue

application.yml

dubbo related parameters: can be viewed in the DubboConfigurationProperties class

server:
  port: 8084

###Give a name as the service name (the name of the service registered in the eureka registry, such as order service)
spring:
  application:
    name: app-account
  datasource:
    url: jdbc:mysql://localhost:3306/test-account
    username: root
    password: root
    # Using druid data sources
    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

## This configuration node is an independent node, not under the spring node
mybatis:
  mapper-locations: classpath:mapping/*.xml  #Note: be sure to correspond to the path of the mapper mapping xml file
  type-aliases-package: com.sid.model  # Note: the path of the corresponding entity class
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql from console

Startup class

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;

    /**
     * Deduct money
     * */
    @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);
    }

}

Business logic 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 and model are generated directly by mybatis plug-in

storage project

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>
                <!-- Exclude self-contained logback rely on -->
                <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 of druid Database connection pool -->
        <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 Automatic code generation plug-in -->
            <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>
                    <!-- So you don't have to generatorConfig.xml Local configuration inside mysql-connector-java Location-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Project directory

Startup class

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

###Give a name as the service name (the name of the service registered in the eureka registry, such as order service)
spring:
  application:
    name: app-storage
  datasource:
    url: jdbc:mysql://localhost:3306/test-storage
    username: root
    password: root
    # Using druid data sources
    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

## This configuration node is an independent node, not under the spring node
mybatis:
  mapper-locations: classpath:mapping/*.xml  #Note: be sure to correspond to the path of the mapper mapping xml file
  type-aliases-package: com.sid.model  # Note: the path of the corresponding entity class
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql from console

RPC implementation class

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;

    /**
     * Commodity deduction inventory
     * */
    @Override
    public String deduct(String commodityCode, int count) {

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

Business 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;

    /**
     * Commodity deduction inventory
     * */
    @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 project

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; Exclude self-contained logback rely on &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 of druid Database connection pool -->
        <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 Automatic code generation plug-in -->
            <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>
                    <!-- So you don't have to generatorConfig.xml Local configuration inside mysql-connector-java Location-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Catalogue

application.yml

server:
  port: 8082

###Give a name as the service name (the name of the service registered in the eureka registry, such as order service)
spring:
  application:
    name: app-order
  datasource:
    url: jdbc:mysql://localhost:3306/test-order
    username: root
    password: root
    # Using druid data sources
    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

## This configuration node is an independent node, not under the spring node
mybatis:
  mapper-locations: classpath:mapping/*.xml  #Note: be sure to correspond to the path of the mapper mapping xml file
  type-aliases-package: com.sid.model  # Note: the path of the corresponding entity class
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql from console


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

Startup class

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 service implementation

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;

    /**
     * Create order
     */
    @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;
    }
}

RPC calls account service in business service

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;

    /**
     * Create order
     */
    @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);

        /**
         * The RPC calls here are synchronous
         * todo You need to write an asynchronous example. This may need to be written in dubbo. feign is synchronous
         * */
        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 project

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 of druid Database connection pool -->
        <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>
                <!-- Exclude self-contained logback rely on -->
                <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 Automatic code generation plug-in -->
            <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>
                    <!-- So you don't have to generatorConfig.xml Local configuration inside mysql-connector-java Location-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Project directory

application.yml

server:
  port: 8085


###Give a name as the service name (the name of the service registered in the eureka registry, such as order service)
spring:
  application:
    name: app-business
  datasource:
    url: jdbc:mysql://localhost:3306/test-business
    username: root
    password: root
    # Using druid data sources
    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

## This configuration node is an independent node, not under the spring node
mybatis:
  mapper-locations: classpath:mapping/*.xml  #Note: be sure to correspond to the path of the mapper mapping xml file
  type-aliases-package: com.sid.model  # Note: the path of the corresponding entity class
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql from console

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

Startup class

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);
    }

}

Business service, RPC calls order service and storage service

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;

    /**
     * purchase
     */
    @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";
    }


}

III. nacos is used as the configuration center

nacos open api 

Take the business project above as an example and make modifications on this basis

pom. Add a dependency to XML

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

application.yml join

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

nacos configuration class

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;
    }
}

Using the configuration in 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();
    }
}

Create configuration file in nacos management interface

Parameter description

Data Id

The default value of Data Id is ${Nacos. Config. Prefix} - ${spring. Profile. Active}$ {nacos.config.file-extension}

nacos. config. The default value of prefix is ${spring.application.name}

nacos. config. The default value of file extension is properties

When spring profiles. If active is not configured, ${spring. Application. Name} properties

If spring is set profiles. Active, while ${spring. Application. Name} exists in Nacos Properties, if ${spring. Application. Name} - ${spring.profiles.active} If the former does not exist, the latter will match automatically

Because Nacos recommends and defaults to spring application. Name as the prefix of Data Id

Group

This is a very flexible configuration item with no fixed regulations. It can be used to distinguish configurations among multiple environments, modules and versions

Namespace

It is recommended to use namespaces to distinguish the configurations of different environments, because using profiles or group s will display the configurations of different environments on one page, while the Nacos console displays the configurations of different namespaces in Tab columns

If you need different configurations for different environments, create a namespace, such as dev

Create the configuration file app business under this namespace

 

Then match the ID of the namespace in the yml of the project

# nacos address
nacos:
  server-address: localhost
  port: 8848
  config:
    server-addr: ${nacos.server-address}:${nacos.port}
    namespace: 48acfc39-0299-4c3e-af1a-ecb8b24ad524  # The namespace ID is not a namespace name to distinguish the dev sit pro environment

In this way, you can read the configuration of the app business file under dev

 

Keywords: Dubbo Spring Boot Spring Cloud Nacos

Added by fredcool on Mon, 07 Feb 2022 12:10:30 +0200