温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringCloud的入门概述以及如何进行Rest微服务案例构建

发布时间:2021-10-09 11:52:50 来源:亿速云 阅读:146 作者:柒染 栏目:大数据

本篇文章给大家分享的是有关SpringCloud的入门概述以及如何进行Rest微服务案例构建,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

SpringCloud

一、SpringCloud入门概述

1、什么是微服务
	提倡将单一的应用程序划分成一组组小的服务。每个服务运行在其独立的自己的进程中。服务间互相协调、互相配合。
	服务之间采用轻量级的通讯机制互相沟通(dubbo是RPC、SpringCloud是基于HTTP的restful api)。
	每个服务都围绕着具体的业务进行构建,都能部署到独立的生产环境中。
	(根据业务拆分成一个个的服务,彻底的去耦合)


2、微服务的优缺点是什么?以及在项目开发中碰到的坑
	优点:
        每一个服务专注聚焦于一个指定的业务功能和需求
        松解耦的
        各服务间可以用不同的语言
		前后端分离
		灵活搭配的数据库:自己的数据库+统一的公共数据库
	缺点:
		服务间通讯成本增加
		数据一致性
		运维难度增加等

3、微服务的技术栈有哪些

	服务开发		springboot、spring、springmvc等	
	服务配置与管理		Netflix公司的Archaius、阿里的Diamond
	服务注册与发现		Eureka、Consul、zookeeper
	服务调用			Rest、RPC、gRPC
	服务熔断器			Hystrix(dashboard服务监控)、Envoy
	负载均衡			Ribbon、Nginx
	服务接口调用			Feign
	消息队列			kafka、RabbitMq、ActiveMq
	服务配置中心管理		SpringCloudConfig、Chef
	服务路由				Zuul
	服务监控				Zabbix、Nagios、Metrics、Spectator
	全链路追踪			Zipkin、Brave、Dapper
	服务部署			Docker、Openstack、Kubernetes
	数据流操作开发包		SpringCloud Stream(封装与Redis\Rabbit\kafka等发送接收消息)
	事件消息总线			SpringCloud Bus

4、springcloud和dubbo有哪些区别
					Dubbo			SpringCloud
	注册中心		zookeeper			Eureka
	调用方式			RPC				REST API
	服务监控		Dubbo-monitor	SpringBoot Admin
	断路器			  -------			Hystrix
	服务网管		 					Zuul
	分布式配置					   SpringCloud config
	服务跟踪					    SpringCloud Sleuth
	消息总线						SpringCloud Bus
	数据流							 SpringCloud stream
	批量任务						SpringCloud Task
	。。。。		。。。。。。。			。。。。。。。

dubbo服务治理

官网

https://spring.io/projects/spring-cloud
https://springcloud.cc	中文社区
https://springcloud.cn	中文官网

SpringCloud的入门概述以及如何进行Rest微服务案例构建

二、Rest微服务构建案例工程

以Dept部门模块做一个微服务通用案例、Consumer消费者[client]通过rest调用Provider提供的服务

结构

cloud:   
	cloud-api					封装整体entity、接口和 公共配置等
    cloud-provider-dept-8001	微服务的服务提供者
    cloud-consumer-dept-80		微服务的服务消费者

1、父工程

new maven project

groupID  			com.lee
artifact id			cloud
packaging			pom

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.lee</groupId>
    <artifactId>cloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--重要POM-->
    <packaging>pom</packaging>

    <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>
            <!--cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--SpringBoot-->
            <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>

</project>

2、cloud-api公共子模块

new maven module

moduleName   cloud-api
parentProject  cloud
groupId      com.lee
artifactId    cloud-api
packaging     jar

创建完成后 父工程POM文件会多了个<module></module>标签

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>cloud</artifactId>
        <groupId>com.lee</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>
    </dependencies>

</project>

Entity

[ 微服务,一定要实现序列化 ]

package com.lee.cloud.entity;

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

import java.io.Serializable;

@Data
@ToString
@Accessors(chain = true)
@NoArgsConstructor
public class Dept implements Serializable {
    private static final long serialVersionUID = 5051248965243297270L;

    private Long  deptno;   //主键
    private String  dname;   //部门名称
    private String  db_source;//来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库

 	public Dept(String dname) {
        this.dname = dname;
    }
}

3、cloud-provider-dept-8001生产者

部门微服务提供者

new maven module

moduleName   cloud--provider-dept-8001
parentProject  cloud
groupId      com.lee
artifactId    cloud--provider-dept-8001
packaging     jar

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>cloud</artifactId>
        <groupId>com.lee</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud--provider-dept-8001</artifactId>


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



</project>

application.yml

server:
  port: 8001

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.lee.cloud.entity             # 所有Entity别名类所在包
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件

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: 123456
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间

mybatis.cfg.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <settings>
        <setting name="cacheEnabled" value="true"/><!-- 二级缓存开启 -->
    </settings>

</configuration>

mysql

DROP DATABASE IF EXISTS cloudDB01;
CREATE DATABASE cloudDB01 CHARACTER SET UTF8;
USE cloudDB01;
CREATE TABLE dept
(
  deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dname VARCHAR(60),
  db_source   VARCHAR(60)
);
 
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
 
SELECT * FROM dept;

接口:dao\mapper\service\controller\

DAO:

package com.lee.cloud.dao;

import com.lee.cloud.entity.Dept;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * springboot整合mybatis
 * 第一种方法:在dao上加@Mapper
 * 第二种方法:在启动类上加@MapperScan
 */
@Mapper
public interface DeptDao {

    public boolean addDept(Dept dept);

    public Dept findById(Long id);

    public List<Dept> findAll();

}

------------------------------------------------------------
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.lee.cloud.dao.DeptDao">

    <select id="findById" resultType="Dept" parameterType="Long">
       select deptno,dname,db_source from dept where deptno=#{deptno};
    </select>

    <select id="findAll" resultType="Dept">
       select deptno,dname,db_source from dept;
    </select>
    
    <insert id="addDept" parameterType="Dept">
       INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE());
    </insert>

</mapper>

----------------------------------------------------------------------
        
SERVICE
        
package com.lee.cloud.service;

import com.lee.cloud.entity.Dept;

import java.util.List;

public interface DeptService {

    public boolean add(Dept dept);

    public Dept    get(Long id);

    public List<Dept> list();

}
--------------------------------------------------------------------------
      
SERVICE IMPL
        
package com.lee.cloud.service.impl;

import com.lee.cloud.dao.DeptDao;
import com.lee.cloud.entity.Dept;
import com.lee.cloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptDao dao ;

    @Override
    public boolean add(Dept dept)
    {
        return dao.addDept(dept);
    }

    @Override
    public Dept get(Long id)
    {
        return dao.findById(id);
    }

    @Override
    public List<Dept> list()
    {
        return dao.findAll();
    }


}
----------------------------------------------------------------------

CONTROLLER
    
package com.lee.cloud.controller;

import com.lee.cloud.entity.Dept;
import com.lee.cloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService service;

    @RequestMapping(value="/dept/add",method= RequestMethod.POST)
    public boolean add(@RequestBody Dept dept)
    {
        return service.add(dept);
    }

    @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET)
    public Dept get(@PathVariable("id") Long id)
    {
        return service.get(id);
    }

    @RequestMapping(value="/dept/list",method=RequestMethod.GET)
    public List<Dept> list()
    {
        return service.list();
    }


}

主启动类APP

package com.lee.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DeptProvider8001_APP {

    public static void main(String[] args) {
        SpringApplication.run(DeptProvider8001_APP.class,args);
    }
}

测试:

http://localhost:8001/dept/list

结果:
[{"deptno":1,"dname":"开发部","db_source":"clouddb01"},
{"deptno":2,"dname":"人事部","db_source":"clouddb01"},
{"deptno":3,"dname":"财务部","db_source":"clouddb01"},
{"deptno":4,"dname":"市场部","db_source":"clouddb01"},
{"deptno":5,"dname":"运维部","db_source":"clouddb01"}]

3、cloud-consumer-dept-80 消费者

部门微服务消费者

new maven module

moduleName   cloud--consumer-dept-80
parentProject  cloud
groupId      com.lee
artifactId    cloud--consumer-dept-80
packaging     jar

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>cloud</artifactId>
        <groupId>com.lee</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-consumer-dept-80</artifactId>
    <description>部门微服务消费者</description>

    <dependencies>
        <dependency><!-- 自己定义的api -->
            <groupId>com.lee</groupId>
            <artifactId>cloud-api</artifactId>
            <version>${project.version}</version>
        </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>

APPLICATION.YML

server:
  port: 80

configBean配置类

package com.lee.cloud.cfgbean;

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

//配置类
@Configuration
public class ConfigBean {

    //RestTemplate提供了多种便捷访问远程HTTP服务的方法
    //是一种简单便捷的访问restful服务模板类,是spring提供的用于访问Rest服务的客户端模板工具集
    //类似JDBCTemplate   RedisTemplate等
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

RestTemplate提供了多种便捷访问远程HTTP服务的方法

是一种简单便捷的访问restful服务模板类,是spring提供的用于访问Rest服务的客户端模板工具集

类似JDBCTemplate RedisTemplate等

controller

package com.lee.cloud.controller;

import com.lee.cloud.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class DeptController_Consumer {

    private static final String REST_URL_PREFIX = "http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value="/consumer/dept/add")
    public boolean add(Dept dept)
    {
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add", dept, Boolean.class);
    }

    @RequestMapping(value="/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id, Dept.class);
    }

    @RequestMapping(value="/consumer/dept/list")
    public List<Dept> list()
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class);
    }

}

启动类:

package com.lee.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DeptConsumer80_App {

    public static void main(String[] args) {
        
        SpringApplication.run(DeptConsumer80_App.class,args);
    }
}

测试:

1、启动provider服务,再启动consumer服务
2、http://localhost/consumer/dept/list
3、http://localhost/consumer/dept/get/1
4、http://localhost/consumer/dept/add?dname=风控部

以上就是SpringCloud的入门概述以及如何进行Rest微服务案例构建,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI