SpringBoot整合dubbo+zookeeper详细完整

目录

 

1、搭建环境

1.1 ZooKeeper

1.2 dubbo-admin

2、搭建项目

2.1 父项目 dubbo-demo-parent

2.2 服务接口 demo-service

2.3 服务提供者demo-provider

2.4 服务消费者demo-consumer

3、测试


案例代码,tomcat,zookeeper,dubbo-admin包已上传,下载地址:https://download.csdn.net/download/qq_43280198/13524427,下文如有错误欢迎指出。

1、搭建环境

  • jdk、maven和tomcat略过。

1.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窗口停留),如下图所示。

SpringBoot整合dubbo+zookeeper详细完整_第1张图片

  • 双击zkServer.cmd启动,不关闭cmd窗口,注册中心就一直开着。

SpringBoot整合dubbo+zookeeper详细完整_第2张图片

1.2 dubbo-admin

建议自己拉取项目编译打包,在网上搜的war大多都启动不了...

  • 官方地址:https://github.com/apache/dubbo/tree/2.5.x,使用git拉取到本地后用IDEA打开。
  • 打开dubbo-admin模块下的dubbo.properties文件,可配置注册中心地址和用户密码(root用户的密码默认是root,guest用户的密码默认是guest),再使用maven打包。

SpringBoot整合dubbo+zookeeper详细完整_第3张图片

启动的话有两种方式(建议使用第一种。第二种需要维持一个IDEA工作空间,有点占用内存...)

  • 第一种:将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/,输入用户名密码即可

SpringBoot整合dubbo+zookeeper详细完整_第4张图片

  • 第二种:idea配置本地tomcat启动dubbo-admin,按照下面图片一步一步操作吧

SpringBoot整合dubbo+zookeeper详细完整_第5张图片

修改tomcat端口

SpringBoot整合dubbo+zookeeper详细完整_第6张图片

SpringBoot整合dubbo+zookeeper详细完整_第7张图片

修改项目访问路径↓,点击apply

SpringBoot整合dubbo+zookeeper详细完整_第8张图片

启动成功会自动打开浏览器访问,输入用户名密码即可

SpringBoot整合dubbo+zookeeper详细完整_第9张图片

2、搭建项目

2.1 父项目 dubbo-demo-parent

  • 项目结构

SpringBoot整合dubbo+zookeeper详细完整_第10张图片

  • pom文件


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.5.RELEASE
         
    

    com.example
    dubbo-demo-parent
    0.0.1-SNAPSHOT
    dubbo-demo-parent
    pom
    Demo project for Spring Boot

    
        demo-service
        demo-provider
        demo-consumer
    

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            com.alibaba
            druid
            1.1.6
        
        
        
            org.projectlombok
            lombok
            1.18.16
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.2.0
        
        
        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            RELEASE
        
    

    
        
        
            
                src/main/resources
            
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                    **/*.yml
                
                false
            
        
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    true
                
            
        
    

    
    
        
            central
            aliyun
            http://maven.aliyun.com/nexus/content/groups/public/
        
        
            springsource-repos
            SpringSource Repository
            https://repo.spring.io/release/
        
        
            spring-snapshots
            Spring Snapshots
            https://repo.spring.io/snapshot
            
                true
            
        
        
            spring-milestones
            Spring Milestones
            https://repo.spring.io/milestone
            
                false
            
        
        
            central-repos
            Central Repository
            https://repo.maven.apache.org/maven2/
        
        
            central-repos2
            Central Repository 2
            https://repo1.maven.org/maven2/
        
    

    
    
        
            aliyun-plugin
            https://maven.aliyun.com/repository/public
            
                true
            
            
                false
            
        
        
            spring-snapshots
            Spring Snapshots
            https://repo.spring.io/snapshot
            
                true
            
        
        
            spring-milestones
            Spring Milestones
            https://repo.spring.io/milestone
            
                false
            
        
    


2.2 服务接口 demo-service

  • 项目结构

SpringBoot整合dubbo+zookeeper详细完整_第11张图片

  • pom文件


	4.0.0
	
		com.example
		dubbo-demo-parent
		0.0.1-SNAPSHOT
	

	demo-service
	0.0.1-SNAPSHOT
	demo-service
	Demo project for Spring Boot

  • 实体类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;
}
  • 服务UserService
package com.example.demoservice.service;

import com.example.demoservice.model.User;

public interface UserService {

    String save(User user);

    String sayHello(String word);

}
  • 配置文件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
  • 然后使用maven将该模块install到本地仓库,服务提供者和服务消费者的pom中都要引入

2.3 服务提供者demo-provider

  • 项目结构

SpringBoot整合dubbo+zookeeper详细完整_第12张图片

  • pom文件


    4.0.0
    
        com.example
        dubbo-demo-parent
        0.0.1-SNAPSHOT
    

    demo-provider
    0.0.1-SNAPSHOT
    demo-provider
    Demo project for Spring Boot

    
        
        
            com.example
            demo-service
            0.0.1-SNAPSHOT
        
        
        
            org.apache.dubbo
            dubbo-spring-boot-starter
            2.7.3
            
                
                    org.slf4j
                    slf4j-log4j12
                
            
        
        
            org.apache.curator
            curator-framework
            4.0.1
        
        
            org.apache.curator
            curator-recipes
            2.8.0
        
        
        
            org.apache.zookeeper
            zookeeper
            3.4.13
            pom
            
                
                    org.slf4j
                    slf4j-log4j12
                
            
        
        
            com.101tec
            zkclient
            0.10
        
    


  • 服务实现类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;
    }
}
  •  UserMapper
package com.example.demoprovider.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demoservice.model.User;

public interface UserMapper extends BaseMapper {
}
  •  UserMapper.xml





  • 配置文件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

  • 启动类,添加@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);
	}
}

2.4 服务消费者demo-consumer

  • 项目结构

SpringBoot整合dubbo+zookeeper详细完整_第13张图片

  • pom文件


	4.0.0
	
		com.example
		dubbo-demo-parent
		0.0.1-SNAPSHOT
	

	demo-consumer
	0.0.1-SNAPSHOT
	demo-consumer
	Demo project for Spring Boot

	
		
		
			com.example
			demo-service
			0.0.1-SNAPSHOT
		
		
		
			org.apache.dubbo
			dubbo-spring-boot-starter
			2.7.3
			
				
					org.slf4j
					slf4j-log4j12
				
			
		
		
			org.apache.curator
			curator-framework
			4.0.1
		
		
			org.apache.curator
			curator-recipes
			2.8.0
		
		
		
			org.apache.zookeeper
			zookeeper
			3.4.13
			pom
			
				
					org.slf4j
					slf4j-log4j12
				
			
		
		
			com.101tec
			zkclient
			0.10
		
	


  • 配置文件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
  • 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页面,此时没有服务提供者和消费者。

SpringBoot整合dubbo+zookeeper详细完整_第14张图片

  • IDEA启动服务提供者demo-provider,刷新dubbo-admin页面,发现有服务注册成功

SpringBoot整合dubbo+zookeeper详细完整_第15张图片

  • IDEA启动服务消费者demo-consumer,再次刷新dubbo-admin页面,发现服务有对应的消费者

SpringBoot整合dubbo+zookeeper详细完整_第16张图片

  • 调用接口测试

SpringBoot整合dubbo+zookeeper详细完整_第17张图片

SpringBoot整合dubbo+zookeeper详细完整_第18张图片

 

你可能感兴趣的:(工作随笔,java,dubbo,zookeeper,spring,boot)