用一个小demo入门SpringCloud微服务

SpringCloud是一个分布式的服务,

那什么是分布式呢?

分布式:将⼀个复杂问题拆分成若⼲个简单的⼩问题,将⼀个⼤型的项⽬架构拆分成若⼲个微服务来协同完成

微服务包含四个主要结构:

eurekaserver注册中心、configserver配置中心、provider服务提供者,consumer服务消费者等模块。

什么是服务注册?
在分布式系统架构中,每个微服务在启动时,将⾃⼰的信息存储在注册中⼼,叫做服务注册。
什么是服务发现?
服务消费者从注册中⼼获取服务提供者的⽹络信息,通过该信息调⽤服务,叫做服务发现。

SpringCloud如何来实现服务注册和服务发现功能呢? 

Spring Cloud 的服务治理使⽤ Eureka 来实现, Eureka Netflflix 开源的基于 REST 的服务治理解决⽅案,Spring Cloud 集成了 Eureka ,提供服务注册和服务发现的功能,可以和基于 Spring Boot 搭建的微服务应⽤轻松完成整合

微服务项目的大致结构是什么?

每一个服务模块都需要在注册中心eurekaserver进行注册。经过注册的服务要在配置中心configserver进行shared配置,配置完成后的服务才能被扫描到。微服务将访问后台数据并与前端进行交互的一个整体拆分成两部分,其中服务消费者通过Feign来调用服务提供者里的数据,从而实现与用户进行交互;服务提供者是用于访问后台数据库,目的是为服务消费者提供后台数据支持。

项目的架构如下:

如何搭建微服务框架?

第一步,环境搭建

新建maven工程,配置pom文件,导入依赖

以下是我的pom.xml文件

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

    <groupId>com.wzx</groupId>
    <artifactId>aispringclouddemo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>eurekaserver</module>
        <module>configserver</module>
        <module>order</module>
        <module>menu</module>
        <module>client</module>
        <module>user</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
    </parent> 
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 解决 JDK 9 以上没有 JAXB API 的问题 -->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>3.0.0-M4</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

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

</dependencies>
    <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2021.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

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

</project>

第二步,搭建注册中心,新建一个注册中心模块Eurekaserver

并修改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>aispringclouddemo</artifactId>
        <groupId>com.wzx</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eurekaserver</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
    </dependencies>

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

</project>

在resource目录下,新建一个application.yml文件,添加内容如下

server:
  port: 8761
eureka:
  client:
   register-with-eureka: false
   fetch-registry: false
   service-url:
    defaultZone: http://localhost:8761/eureka/

eureka.client.register-with-eureka :是否将当前的 Eureka Server 服务作为客户端进⾏注册。 

eureka.client.fetch-fegistry :是否获取其他 Eureka Server 服务的数据。
eureka.client.service-url.defaultZone :注册中心的访问地址。

创建一个EurekaserverApplication启动类

package com.wzx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class,args);
    }
}
@SpringBootApplication :声明该类是 Spring Boot 服务的⼊口。
@EnableEurekaServer :声明该类是⼀个 Eureka Server 微服务,提供服务注册和服务发现功能,即注册中心。
如图:

 第三步:搭建配置中心,新建一个配置中心模块configserver

并修改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>aispringclouddemo</artifactId>
        <groupId>com.wzx</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>configserver</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

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

</project>

在resource目录下,新建一个application.yml文件,添加内容如下:

server:
  port: 8762
spring:
  application:
    name: configserver
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/shared
profiles.active :配置⽂件的获取⽅式
cloud.config.server.native.search-locations :本地配置⽂件存放的路径
在resources 路径下创建 shared ⽂件夹,里面保存配置文件,比如其中menu-dev是服务提供者的配置文件如下:
server:
  port: 8020
spring:
  application:
    name: menu
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123
eureka:
  client:
    service-url:
      defalutZone: http://localhost:8761/eureka/
    instance:
      prefer-ip-address: true
mybatis:
  mapper-locations: classpath:/mapping/*.xml

创建一个ConfigServerApplication启动类

package com.wzx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class,args);
    }
}

总结构如下:

 

第四步:添加服务提供者provider

以服务提供者menu为例: 

首先是添加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>aispringclouddemo</artifactId>
        <groupId>com.wzx</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>menu</artifactId>

    <!--在注册中心进行注册,成为一个服务提供者-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>3.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!--读取配置中心的配置文件-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>2.2.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>3.0.2</version>
        </dependency>

    </dependencies>

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

</project>

然后,新建bootstrap.yml文件

spring:
  application:
    name: menu
  profiles:
    active: dev
  cloud:
    config:
      uri: http://localhost:8762
      fail-fast: true

接下来就是,创建启动类MenuApplication

package com.wzx;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.wzx.repository")
public class MenuApplication {
    public static void main(String[] args) {
        SpringApplication.run(MenuApplication.class,args);
    }
}

创建Controller包,并新建一个MenuHandler类

package com.wzx.controller;

import com.wzx.entity.Menu;
import com.wzx.entity.MenuVO;
import com.wzx.entity.Type;
import com.wzx.repository.MenuRepository;
import com.wzx.repository.TypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/menu")
public class MenuHandler {
    @Value("${server.port}")
    private String port;

    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private TypeRepository typeRepository;

    @GetMapping("/index")
    public String index(){
        return "menu的端口:" +this.port;
    }

    @GetMapping("/findAll/{index}/{limit}")
    public MenuVO findAll(@PathVariable ("index")int index,@PathVariable("limit")int limit){
        return new MenuVO(0,"", menuRepository.count(), menuRepository.findAll(index,limit));
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        menuRepository.deleteById(id);
    }

    @GetMapping("/findTypes")
    public List<Type> findTypes(){
        return typeRepository.findAll();
    }

    @PostMapping("/save")
    public void save(@RequestBody Menu menu){
        menuRepository.save(menu);
    }

    @GetMapping("/findById/{id}")
    public Menu findById(@PathVariable("id") long id){
        return menuRepository.findById(id);
    }

    @PutMapping("/update")
    public void update(@RequestBody Menu menu){
        menuRepository.update(menu);
    }
}

创建实体类包entity,新建menu类、menuVO类、Tpye类

package com.wzx.entity;

import lombok.Data;

@Data
public class Menu {
    private long id;
    private String name;
    private double price;
    private String flavor;
    private Type type;
}
package com.wzx.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class MenuVO {
    private int code;
    private String msg;
    private int count;
    private List<Menu> data;
}
package com.wzx.entity;

import lombok.Data;

@Data
public class Type {
    private long id;
    private String name;
}

新建repository包,以及新建MenuRepository、TypeRepository接口

package com.wzx.repository;

import com.wzx.entity.Type;

import java.util.List;

public interface TypeRepository {
    public Type findById(long id);
    public List<Type> findAll();
}
package com.wzx.repository;

import com.wzx.entity.Menu;

import java.util.List;

public interface MenuRepository {
    public List<Menu> findAll(int index,int limit);
    public int count();
    public Menu findById(long id);
    public void save(Menu menu);
    public void update(Menu menu);
    public void deleteById(long id);

}

在resource里新建mapping包,将sql语句在与repository接口对应的xml文件中实现

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wzx.repository.MenuRepository">
    
    <resultMap id="menuMap" type="com.wzx.entity.Menu">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="price" property="price"></result>
        <result column="flavor" property="flavor"></result>
        <association property="type" select="com.wzx.repository.TypeRepository.findById" column="tid"></association>
    </resultMap>
    <select id="findAll" resultMap="menuMap">
        select * from t_menu limit #{param1},#{param2}
    </select>

    <select id="count" resultType="int">
        select count(*) from t_menu;
    </select>

    <insert id="save" parameterType="com.wzx.entity.Menu">
        insert into t_menu(name,price,flavor,tid) values(#{name},#{price},#{flavor},#{type.id})
    </insert>

    <select id="findById" resultMap="menuMap">
        select * from t_menu where id = #{id}
    </select>

    <update id="update" parameterType="com.wzx.entity.Menu">
        update t_menu set name = #{name},price = #{price},flavor = #{flavor},tid = #{type.id} where id = #{id}
    </update>

    <delete id="deleteById" parameterType="long">
        delete from t_menu where id = #{id}
    </delete>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wzx.repository.TypeRepository">

    <select id="findById" resultType="com.wzx.entity.Type">
        select * from t_type where id = #{id}
    </select>

    <select id="findAll" resultType="com.wzx.entity.Type">
        select * from t_type
    </select>
</mapper>

测试一下,如果能够访问到后台数据了,那么这个服务提供者就是搭建成功了

第五步:搭建服务消费者Consumer

服务消费者是与前端进行交互的,服务消费者是通过Feign来调用服务提供者的

以服务消费者client为例:

新建一个连接menu模块的MenuFeign:

package com.wzx.feign;

import com.wzx.entity.Menu;
import com.wzx.entity.MenuVO;
import com.wzx.entity.Type;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@FeignClient(value = "menu")
public interface MenuFeign {

    @GetMapping("/menu/findAll/{index}/{limit}")
    public MenuVO findAll(@PathVariable("index") int index, @PathVariable("limit")int limit);

    @DeleteMapping("/menu/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id);

    @GetMapping("/menu/findTypes")
    public List<Type> findTypes();

    @PostMapping("/menu/save")
    public void save(Menu menu);

    @GetMapping("/menu/findById/{id}")
    public Menu findById(@PathVariable long id);

    @PutMapping("/menu/update")
    public void update(Menu menu);
}

在resource包中添加与前端交互的静态页面static

其中inde.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}" media="all">
</head>
<body>
<div class="layui-container" style="width: 700px;height: 600px;margin-top: 0px;padding-top: 60px;">

    <div style="margin-left: 460px; width: 200px;">
        欢迎回来!&nbsp;&nbsp;&nbsp;<button class="layui-btn layui-btn-warm layui-btn-radius">退出</button></a>
    </div>

    <table class="layui-hide" id="test" lay-filter="test"></table>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="update">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    <script th:src="@{/layui/layui.js}" charset="utf-8"></script>
    <script>
        layui.use('table', function(){
            var table = layui.table;

            table.render({
                elem: '#test'
                ,url:'/menu/findAll'
                ,title: '菜单列表'
                ,cols: [
                    [
                        {field:'id', width:100, title: '编号', sort: true}
                        ,{field:'name', width:170, title: '菜品'}
                        ,{field:'price', width:100, title: '单价'}
                        ,{field:'flavor', width:70, title: '口味'}
                        ,{field:'tid',width:100,  title: '分类',templet:function(data){
                            return data.type.name
                        }
                    }
                        ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:130}
                    ]
                ]
                ,page: true
            });

            //监听行工具事件
            table.on('tool(test)', function(obj){
                var data = obj.data;
                if(obj.event === 'update'){
                    window.location.href="/menu/findById/"+data.id;
                }
                if(obj.event === 'del'){
                    layer.confirm('确定要删除吗?',function (index) {
                        window.location.href="/menu/deleteById/"+data.id;
                        layer.close(index);
                    });
                }
            });
        });
    </script>
</div>
</body>
</html>

在页面如果能够通过路径访问到index页面,并且能够连接到后台接口,那么这个服务消费者就实现了。

总结:

在学习这个SpringCloud小demo的过程中,我对SpringCloud这个微服务框架有了大致的了解,他是分布式和集群,如果我用我浅薄的知识概括一下SpringCloud的话,我认为SpringCloud分布式就是多个springboot服务分别部署,并且整合在一起。同时,我了解了如何去搭建SpringCloud项目。

坚定目标,日日精进,必有所成。共勉! !

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值