Spring cloud Alibaba microservice Practice II - service registration

Posted by kamasheto on Tue, 10 Dec 2019 22:52:57 +0100

Introduction: in the previous article, we have prepared the basic components based on spring cloud Alibaba. The main content of this issue is to register all services into Nacos, and enable account service and product service to provide basic addition, deletion, modification and query capabilities.

Basic framework construction

Create a multi module project in your IDEA. The overall screenshot of the project is as follows:

  • Define the basic component version in the main pom, and use dependency management to introduce version dependency.
<properties>
    <java.version>1.8</java.version>
    <spring-boot.version>2.1.9.RELEASE</spring-boot.version>
    <springcloud-alibaba.version>0.9.0.RELEASE</springcloud-alibaba.version>
    <mybatis-plus.version>3.1.1</mybatis-plus.version>
    <mysql.version>5.1.47</mysql.version>
    <encoding>UTF-8</encoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--database-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${springcloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  • Introduce specific dependencies into the Service module. I am used to using log4j2 as the log component, and choose it according to your habits
<dependencies>
    <!--Spring Boot-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <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>

    <!--Spring Cloud Alibaba-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!--database-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

</dependencies>

Integrated Nacos registry

  • Introducing spring cloud starter Alibaba Nacos discovery, the previous step has been completed;
  • Modify the configuration file application.yml to configure the service address of nacos (pay attention to modifying the service port);
server:
  port: 8010
spring:
  application:
    name: account-service
  cloud:
    nacos:
      discovery:
        server-addr: 10.0.10.48:8848/
  • Add @ EnableDiscoveryClient annotation on the project startup class
@SpringBootApplication
@RestController
@EnableDiscoveryClient
public class AccountServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(AccountServiceApplication.class, args);
    }
}

In three simple steps, the service is registered in Nacos, and the account service, product service, and order service are respectively started. After the start, you can visit the address of Nacos server http://10.0.10.48:8848/nacos to find that the service is registered normally.

Provide the ability of basic addition, deletion, modification and query

Data preparation

This series of articles are based on account service, product service and order service, so we have prepared these three basic table structures first.

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for order
-- ----------------------------
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ORDER_NO` varchar(255) DEFAULT NULL,
  `ACCOUNT_CODE` varchar(255) DEFAULT NULL,
  `PRODUCT_CODE` varchar(255) DEFAULT NULL,
  `COUNT` int(11) DEFAULT '0',
  `AMOUNT` decimal(10,2) DEFAULT '0.00',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `PRODUCT_CODE` varchar(255) DEFAULT NULL COMMENT 'Code',
  `PRODUCT_NAME` varchar(255) DEFAULT NULL COMMENT 'Name',
  `COUNT` int(11) DEFAULT '0' COMMENT 'Inventory quantity',
  `PRICE` decimal(10,2) DEFAULT '0.00' COMMENT 'Unit Price',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `UK_PRODUCT_CODE` (`PRODUCT_CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product` VALUES ('1', 'P001', 'Notebook', '10', '3000.00');
INSERT INTO `product` VALUES ('2', 'P002', 'Wrist Watch', '5', '250.00');
INSERT INTO `product` VALUES ('3', 'P003', 'keyboard', '50', '100.00');
INSERT INTO `product` VALUES ('4', 'P004', 'Spicy strips', '1000', '0.50');

DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ACCOUNT_CODE` varchar(255) DEFAULT NULL,
  `ACCOUNT_NAME` varchar(255) DEFAULT NULL,
  `AMOUNT` decimal(10,2) DEFAULT '0.00',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `UK_ACCOUNT_CODE` (`ACCOUNT_CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1', 'javadaily', 'JAVA RI Zhi Lu', '10000.00');

code implementation

At present, we only provide the ability of simple CRUD externally, so I will not post this code. We only provide our external interface Controller, Service layer and Dao layer, which can be implemented by ourselves according to the technology stack. Here I would like to recommend mybatis-plus Plug in can greatly improve the implementation efficiency of CRUD, and those who are interested can go to the official website to view documents.

  • Interface Controller layer
@RestController
@Log4j2
public class AccountController {
    @Autowired
    private AccountService accountService;

    @GetMapping("/account/{accountCode}")
    public AccountVO getByCode(@PathVariable String accountCode){
        log.info("get account detail,accountCode is :{}",accountCode);
        return accountService.selectByCode(accountCode);
    }

    @PostMapping("/account/update")
    public AccountVO update(AccountVO accountVO){
        log.info("update account:{}",accountVO);
        return accountService.updateAccount(accountVO);
    }

    @PostMapping("/account/insert")
    public AccountVO insert(AccountVO accountVO){
        log.info("insert account:{}",accountVO);
        return accountService.insertAccount(accountVO);
    }

    @PostMapping("/account/delete")
    public int delete(@RequestParam String accountCode){
        log.info("delete account,accountCode is {}",accountCode);
        return accountService.deleteAccount(accountCode);
    }
}

The code in the controller layer is ugly, but it doesn't matter. We will change it later. After all, writing code is a continuous process. In a word, continuous attention is right.

  • Interface list

    Here is the use of restful toolkit, a plug-in of Idea, for demonstration, and it is also very convenient for interface testing, which is also recommended to you.

So far, all services have been registered in the registration center Nacos and can provide basic addition, deletion, modification and query capabilities to the outside world. Then the "spring cloud Alibaba microservice practice - service registration" chapter of this issue should be over. We are bound to see you next time!

Serial articles

Welcome to scan code concern WeChat public number or Personal blog

Topics: Java Spring MySQL Mybatis