一、名词解释
1、RPC
RPC(Remote Procedure Call)—远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。
2、SOA
SOA(面向服务的架构)Service-Oriented Architecture:面向服务的架构(SOA)是一个组件模型,它将应用程序的不同功能单元(称为服务)进行拆分,并通过这些服务之间定义良好的接口和契约联系起来。
二、dubbo
1、概念
Dubbo 是一款高性能、轻量级的开源Java RPC框架,
- 一款分布式服务框架
- 高性能和透明化的RPC远程服务调用方案
- SOA服务治理方案
它提供了三大核心能力:
面向接口的远程方法调用,
智能容错和负载均衡,
服务自动注册和发现。
2、dubbo连接方式
客户端和服务端有三种连接方式:
广播、直连和zookeeper注册中心
广播:
配置文件中:
服务端:
<!-- 使用multicast广播暴露服务地址 -->
<dubbo:registry address="multicast://127.0.0.1:8081" />
客户端:
<!-- 使用multicast广播暴露服务地址 -->
<dubbo:registry address="multicast://127.0.0.1:8082" />
直连:
配置文件中:
服务端:
<!-- 使用multicast广播暴露服务地址 -->
<dubbo:registry address="N/A" />
客户端:
<!-- 使用multicast广播暴露服务地址 -->
<dubbo:registry address="multicast://127.0.0.1:8082" />
zookeeper注册中心:
Dubbo注册中心和广播注册中心配置类似,不过需要指定注册中心类型和注册中心地址,这个时候就不是吧服务信息进行广播了,而是高速注册中心进行管理,这个时候我们就需要一个注册中心。
3、Dubbo 架构流程图
****节点角色说明:****:
Provider 服务提供方
Registry 注册中心
Consumer 服务消费方
Monitor 统计服务调用次数和调用时间的监控中心
调用流程
1、启动服务提供者。
2、服务提供者在启动时,向注册中心注册自己提供的服务。
3、服务消费者在启动时,向注册中心订阅自己所需的服务。
4、注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者。
5、服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失败,再选另一台调用。
6、服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心。
注册中心
注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小。
服务提供方:针对所提供的服务到注册中心发布。
服务消费方:到服务中心订阅所需的服务。
对于任何一方,不论服务提供方或者服务消费方都有可能同时兼具两种角色,即需要提供服务也需要消费服务。
三、Zookeeper
1、介绍:
官方推荐使用 zookeeper作为注册中心。
注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小。
Zookeeper 是 Apacahe Hadoop 的子项目,是一个树型的目录服务,支持变更推送,适合作为Dubbox 服务的注册中心,工业强度较高,可用于生产环境。
ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务,
是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。
它是一个为分布式应用提供一致性服务的软件,
提供的功能包括:配置维护、域名服务、分布式同步、组服务等。
2、Zookeeper 在Linux系统的安装
安装步骤:
1、上传 zookeeper 的压缩包(zookeeper-3.4.6.tar.gz)到 linux 系统。
rz ...
2、解压缩压缩包
tar -zxvf zookeeper-3.4.6.tar.gz
3、进入 zookeeper-3.4.6 目录,创建 data 文件夹。
mkdir data
4、进入conf目录 ,把 zoo_sample.cfg 改名为 zoo.cfg
cd conf
mv zoo_sample.cfg zoo.cfg
5、打开zoo.cfg , 修改 data 属性:
dataDir=/root/zookeeper-3.4.6/data
3、服务启动
进入bin目录,启动服务输入命令
./zkServer.sh start
关闭服务输入命令
./zkServer.sh stop
查看状态:
./zkServer.sh status
四、Demo
1、搭建环境
ZooKeeper:
- 官方下载地址:https://mirror.bit.edu.cn/apache/zookeeper,选择想要版本后下载带-bin的压缩文件。
- 下载后解压,进入conf文件夹,复制一份zoo_sample.cfg,改名为zoo.cfg。
- zoo.cfg内容如下,注意修改自己的地址。
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=自己的地址/tmp
dataDirLog=自己的地址/log
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
-
进入bin文件夹,选中zkServer.cmd,右键->编辑,在最后添加一行 pause并保存(作用:启动后cmd窗口停留),如下图所示。
-
双击zkServer.cmd启动,不关闭cmd窗口,注册中心就一直开着。
dubbo-admin:
- 官方地址:https://github.com/apache/dubbo/tree/2.5.x,使用git拉取到本地后用IDEA打开。
- 打开dubbo-admin模块下的dubbo.properties文件,可配置注册中心地址和用户密码(root用户的密码默认是root,guest用户的密码默认是guest),再使用maven打包。
- 将dubbo-admin的war包放到本地tomcat中启动
- 找到dubbo-admin/target下的dubbo-admin-2.5.10.war,复制到tomcat的webapps目录下
- 进入tomcat的conf目录,打开server.xml文件,找到标签,修改port为8090(一定要修改端口,tomcat默认的8080端口被zookeeper用到了)
- 进入tomcat的bin目录,双击startup.bat启动,看到部署完成信息后关闭窗口,再进入webapps目录下,会发现多了dubbo-admin-2.5.10文件夹
- 直接双击startup.bat启动tomcat,启动成功后浏览器访问http://localhost:8090/dubbo-admin-2.5.10/,输入用户名密码即可
- 或者,删除webapps目录下的ROOT,将dubbo-admin-2.5.10文件夹重命名为ROOT,再双击startup.bat启动tomcat,启动成功后浏览器访问http://localhost:8090/,输入用户名密码即可
2、搭建项目
1、父项目 dubbo-demo-parent
1、项目结构
2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>dubbo-demo-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dubbo-demo-parent</name>
<packaging>pom</packaging>
<description>Demo project for Spring Boot</description>
<modules>
<module>demo-service</module>
<module>demo-provider</module>
<module>demo-consumer</module>
</modules>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<scope>test</scope>
</dependency>
<!--JDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
<build>
<!-- 让 mapper.xml 可被src/main/resources 扫描到 -->
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
<!--远程仓库-->
<repositories>
<repository>
<id>central</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</repository>
<repository>
<id>springsource-repos</id>
<name>SpringSource Repository</name>
<url>https://repo.spring.io/release/</url>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>central-repos</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2/</url>
</repository>
<repository>
<id>central-repos2</id>
<name>Central Repository 2</name>
<url>https://repo1.maven.org/maven2/</url>
</repository>
</repositories>
<!--插件远程仓库-->
<pluginRepositories>
<pluginRepository>
<id>aliyun-plugin</id>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
2、服务接口 demo-service
1、项目结构
2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>dubbo-demo-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>demo-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-service</name>
<description>Demo project for Spring Boot</description>
</project>
3、实体类User
package com.example.demoservice.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName(value = "user")
public class User implements Serializable {
private static final long serialVersionUID = -7291508790203233996L;
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String name;
private Integer age;
}
4、服务UserService
package com.example.demoservice.service;
import com.example.demoservice.model.User;
public interface UserService {
String save(User user);
String sayHello(String word);
}
5、配置文件application.yml
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&failOverReadOnly=false&useSSL=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: root
password: 123456
3、服务提供者demo-provider
1、项目结构
2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>dubbo-demo-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>demo-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-provider</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<!--demo-service-->
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--dubbo-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.3</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<!--zookeeper-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
</dependencies>
</project>
3、服务实现类UserServiceImpl
@Service注解为dubbo的
package com.example.demoprovider.service.impl;
import com.example.demoprovider.mapper.UserMapper;
import com.example.demoservice.model.User;
import com.example.demoservice.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Service
@Component
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public String save(User user) {
userMapper.insert(user);
return "success";
}
@Override
public String sayHello(String word) {
return "hello "+word;
}
}
4、UserMapper
package com.example.demoprovider.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demoservice.model.User;
public interface UserMapper extends BaseMapper<User> {
}
5、UserMapper.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.example.demoprovider.mapper.UserMapper">
</mapper>
6、配置文件application.yml
配置应用名和zookeeper地址
server:
port: 8081 #端口
servlet:
context-path: /demo-provider #访问项目名称
tomcat:
uri-encoding: UTF-8
max-connections: 10000 # tomcat最大连接数
threads:
max: 200 #tomcat最大线程数
dubbo:
application:
name: demo-provider
registry:
address: zookeeper://localhost:2181
scan:
base-packages: com.example.demoprovider.service
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&failOverReadOnly=false&useSSL=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: root
password: 123456
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
connection-timeout: 60000
validation-timeout: 3000
login-timeout: 5
max-lifetime: 60000
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
mybatis-plus:
# 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
mapper-locations: classpath*:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.example.demoprovider.model
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#mp2.3+ 全局表前缀 mp_
#table-prefix: mp_
#刷新mapper 调试神器
refresh-mapper: false
#数据库大写下划线转换
#capital-mode: true
#逻辑删除配置(下面3个配置)
logic-delete-value: 4
logic-not-delete-value: 0
configuration:
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull, oracle数据库必须配置
jdbc-type-for-null: 'null'
#log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
pagehelper:
helperDialect: mysql
reasonable: false #设置为true当页码大于最大页码时会合理化为当前最大页码
supportMethodsArguments: true
params: count=countSql
7、启动类
添加@EnableDubbo
package com.example.demoprovider;
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.example.demoprovider.mapper")
public class DemoProviderApplication {
public static void main(String[] args) {
SpringApplication.run(DemoProviderApplication.class, args);
}
}
4、服务消费者demo-consumer
1、项目结构
2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>dubbo-demo-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>demo-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-consumer</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<!--demo-service-->
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--dubbo-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.3</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<!--zookeeper-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
</dependencies>
</project>
3、配置文件application.yml
配置应用名和zookeeper地址,注意端口冲突
server:
port: 8082 #端口
servlet:
context-path: /demo-consumer #访问项目名称
tomcat:
uri-encoding: UTF-8
max-connections: 10000 # tomcat最大连接数
threads:
max: 200 #tomcat最大线程数
dubbo:
application:
name: demo-consumer
registry:
address: zookeeper://localhost:2181
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&failOverReadOnly=false&useSSL=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: root
password: 123456
4、UserController
消费服务
package com.example.democonsumer.controller;
import com.example.demoservice.model.User;
import com.example.demoservice.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Reference //该注解是dubbo提供的
private UserService userService;
@GetMapping("/say/{word}")
public String sayWord(@PathVariable String word) {
return userService.sayHello(word);
}
@GetMapping("/saveUser")
public String save() {
User user = new User();
user.setName("admin");
user.setAge(22);
return userService.save(user);
}
}
3、测试
- 启动zookeeper,启动tomcat,打开dubbo-admin页面,此时没有服务提供者和消费者。
- IDEA启动服务提供者demo-provider,刷新dubbo-admin页面,发现有服务注册成功
- IDEA启动服务消费者demo-consumer,再次刷新dubbo-admin页面,发现服务有对应的消费者