Spring cloud: Basics

Spring cloud: Basics

Springcloud is an implementation framework of microservice architecture. It is not only a framework, but also an ecology. It contains many technologies. These technologies are combined to form our microservice architecture application.

1.SpringCloud vs Dubbo

The biggest difference: spring cloud abandons Dubbo's RPC communication and adopts HTTP based rest. Strictly speaking, these two methods have their own advantages and disadvantages. Although to some extent, the latter sacrifices the performance of service calls, it also avoids the problems caused by the above-mentioned native RPC. Moreover, rest is more flexible than RPC. The dependence of service providers and callers only depends on a contract, and there is no strong dependence at the code level, which is more appropriate in the microservice environment emphasizing rapid evolution. Obviously, the function of spring cloud is more powerful and covers a wider range than Dubbo. As a fist project of spring, it can also be perfectly integrated with other spring projects such as spring framework, spring boot, spring data and spring batch, which are very important for microservices. The microservice architecture built by Dubbo is like assembling a computer. We have a high degree of freedom of choice in all links, but the final result is likely to fail because of the poor quality of a memory, which is always worrying. However, if you are an expert, these are not problems; Spring cloud is like a brand machine. Under the integration of spring source, it has done a lot of compatibility tests to ensure that the machine has higher stability. However, if you want to use something other than the original components, you need to have a sufficient understanding of its foundation.

2. Examples of micro service building

We have prepared four modules, and then these four modules are the parent for unified project management, a public API, such as a common entity class, a service provider and a service consumer.

In this way, we have formed a simple microservice architecture program. The next step is to build this framework step by step. Here, idea is used to build the project.

1. Create a parent project

First, we create a maven project. What we should pay attention to is that when we generate the project again, we should choose POM instead of jar or war. Then the project will automatically generate a pile of folders. In fact, we only need the POM file, because we only need version control instead of writing code. Then we will delete the Java and test folders.

[image upload failed... (image-a9312c-1527576686529)]

Now that our parent project is created, we need to do some version dependent processing. We need to add the following contents to the POM file.

<?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.lwen</groupId>
    <artifactId>parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <!--我们的子模块-->
    <modules>
        <module>cloud-api</module>
        <module>provider-dept-8001</module>
        <module>consumer-dept-80</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.5.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>MysqL</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.0.4</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.31</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>microservicecloud</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <delimiters>
                        <delimit>$</delimit>
                    </delimiters>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Note that because my POM file is the POM of projects created by all projects, my sub modules here are added later and can be deleted directly. These things will be generated automatically when creating sub modules.

2. Create a public API

Then right-click the created parent project to create a new module, and then select Maven for the project structure. Note that we can select the parent project when creating the project. Here we select the created parent project.

[picture upload failed... (image-b6b3e0-1527576686529)]

[image upload failed... (image-627ee1-1527576686529)]

Then the generated project will have the following text:

<parent>
    <artifactId>parent</artifactId>
    <groupId>com.lwen</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

Then, after we add some common dependencies, our POM will look like this:

<?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>parent</artifactId>
        <groupId>com.lwen</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-api</artifactId>

    <dependencies><!-- 当前Module需要用到的jar包,按自己需求添加,如果父类已经包含了,可以不用写版本号 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>
</project>

OK, now that our basic configuration has been configured, we can write code in the API. The API we need to share here is actually our entity class. In fact, there are many more. Here we just take the entity class as an example.

Create an entries package, and then create an entity class:

package entries;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Accessors(chain = true)
//必须实现序列化接口
public class Dept implements Serializable {
    private Long deptno;
    private String dname;
    private String db_source;
}

Because we added the dependency of pepper above, the entity class here is very simple.

When this step is completed, it should be such a structure, and then we can start the creation of producers.

3. Producers

In fact, we should include a complete web layer in the producer, that is, we need to have a complete controller, service and Dao, and then our controller is used to call later consumers, because our spring cloud is based on rest requests.

Similarly, we create a maven project, import the parent project, and then import the dependencies:

1. Import dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>parent</artifactId>
        <groupId>com.lwen</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lwen</groupId>
    <artifactId>provider-dept-8001</artifactId>


    <dependencies>
        <!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
        <dependency>
            <groupId>com.lwen</groupId>
            <artifactId>cloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>MysqL</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>

2. Configure the springboot configuration file

server:
  port: 8001

spring:
   application:
    name: cloud-dept
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.MysqL.Driver              # MysqL驱动包
    url: jdbc:MysqL://localhost:3306/cloudDB01              # 数据库名称
    username: root
    password:
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间
      
 mybatis:
  configuration:
    map-underscore-to-camel-case: true

3.dao

package lwen.dao;


import lwen.entries.Dept;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DeptDao {
    @Select("select * from clouddb01.dept")
    public List<Dept> findAll();

    @Insert("insert into clouddb01.dept(name,db_name) values (#{name},database())")
    boolean insertDept(Dept dept);
}

4.Service

package lwen.service;

import lwen.dao.DeptDao;
import lwen.entries.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptService {
    @Autowired
    DeptDao deptDao;

    public List<Dept> findAll() {
        return deptDao.findAll();
    }

    public Boolean insertDept(Dept dept) {
        return deptDao.insertDept(dept);
    }
}

5.controller

package com.lwen.controller;

import entries.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lwen.service.DeptService;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    DeptService deptService;

    @GetMapping("/dep")
    public List<Dept> list() {
        return deptService.list();
    }

    @GetMapping("/dep/add")
    public Integer insert(Dept dept) {
        return deptService.add(dept);
    }
}

4. Consumers

As above, create a module to complete the writing of consumers.

In fact, consumers only have one controller. This is because our real business logic is encapsulated in our micro services, so there is no subsequent service and Dao.

1. Import dependency

<?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>parent</artifactId>
        <groupId>com.lwen</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lwen</groupId>
    <artifactId>consumer-dept-80</artifactId>

    <dependencies>
        <dependency><!-- 自己定义的api -->
            <groupId>com.lwen</groupId>
            <artifactId>cloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- Ribbon相关 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>

2. Configuration file

server:
  port: 81

3.config

package com.lwen.config;

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

@Configuration
public class BeanConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

In this place, I use javaconfig to configure a resttemplate bean. In fact, this thing is the same as redistemplate and JDBC we used to contact before. It is a tool to simplify the operation. Here is to simplify our rest request operation, which is equivalent to an HTTP client.

4.Controller

package com.lwen.controller;


import entries.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class DeptController {

    public static final String PREFIX_URL = "http://localhost:8001/";
    @Autowired
    RestTemplate restTemplate;



    @GetMapping("/list")
    public List list() {
        return restTemplate.getForObject(PREFIX_URL + "dep",List.class);
    }

    @GetMapping("/dep/add")
    public Integer add(Dept dept) {
        return restTemplate.getForObject(PREFIX_URL + "dep/add",Integer.class);
    }
}

OK, now that our project has been built, the current directory structure should be as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>