springboot整合dubbo,集成mongodb实现文件上传服务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoxiangzi520/article/details/85597378

一、dubbo概述

     Dubbo是阿里巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和 Spring框架无缝集成。

     Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。核心部件:Remoting: 网络通信框架,实现了 sync-over-async 和request-response 消息机制。RPC: 一个远程过程调用的抽象,支持负载均衡、容灾和集群功能。Registry: 服务目录框架用于服务的注册和服务事件发布和订阅。

特性:

(1)面向接口代理的高性能RPC调用

提供高性能的基于代理的远程调用能力,服务以接口为粒度,为开发者屏蔽远程调用底层细节。

(2)智能负载均衡

内置多种负载均衡策略,智能感知下游节点健康状况,显著减少调用延迟,提高系统吞吐量。

(3)  服务自动注册与发现

支持多种注册中心服务,服务实例上下线实时感知。

   (4)  高度可扩展能力

遵循微内核+插件的设计原则,所有核心能力如Protocol、Transport、Serialization被设计为扩展点,平等对待内置实现和第三方实现。

(5)  运行期流量调度

内置条件、脚本等路由策略,通过配置不同的路由规则,轻松实现灰度发布,同机房优先等功能。

(6)  可视化的服务治理与运维

提供丰富服务治理、运维工具:随时查询服务元数据、服务健康状态及调用统计,实时下发路由策略、调整配置参数。

服务注册中心用的是zookeeper,不会安装的请看:https://blog.csdn.net/u012702547/article/details/77569325

二、服务提供者

这里我用的是springboot+dubbo+mybatis,dubbo采用的是xml的配置方式,没有采用注解。

项目目录结构如下:

展开详细如下:

1.创建maven项目file-service,此服务提供者对外提供文件上传下载服务。

file-service项目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>
    <packaging>pom</packaging>
    <modules>
        <module>file_api</module>
    </modules>
    <groupId>com.jp.common</groupId>
    <artifactId>file_service</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>file_service</name>

    <dependencies>
        <dependency>
            <groupId>com.jp</groupId>
            <artifactId>framework</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

framework为通用组件包,下载地址:https://github.com/yangfeng005/framework,maven打包安装即可。

2.新建maven模块file-api作为服务的提供接口,包含消费端调用所需的实体等,这时一个公用的模块,消费端和服务端共享的模块。

3.新建springboot模块file-provider,pom.xml加入如下配置:

        <!--mongodb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.5.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.1</version>
        </dependency>
        <dependency>
            <groupId>com.jp.common</groupId>
            <artifactId>file_api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

xml最后引入公共的maven模块。 

application.properties增加zookeeper地址:

spring.profiles.active=dev
dubbo.registry.address=zookeeper://192.168.2.185:2181

4.服务接口:

package com.jp.common.file.service;

import com.jp.common.file.entity.customized.FileInfoAO;
import com.jp.framework.common.model.ServiceResult;

public interface IFileService {

    /**
     * base64字符串图片上传
     *
     * @param base64Str
     * @return
     */
    ServiceResult<FileInfoAO> base64StrUpload(String base64Str);

  
}

 5.接口实现类:  Service注解为spring的注解

package com.jp.common.file.provider.service.impl;

import com.jp.common.file.entity.customized.FileInfoAO;
import com.jp.common.file.service.IFileService;
import com.jp.framework.common.model.ServiceResult;
import com.jp.framework.common.model.ServiceResultHelper;
import com.mongodb.gridfs.GridFSFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileService implements IFileService {

    // 获得SpringBoot提供的mongodb的GridFS对象
    @Autowired
    private GridFsTemplate gridFsTemplate;


    /**
     * base64字符串图片上传
     *
     * @param base64Str
     * @return
     */
    @Override
    public ServiceResult<FileInfoAO> base64StrUpload(String base64Str) {
        if (StringUtils.isEmpty(base64Str)) {
            return ServiceResultHelper.genResultWithFaild("base64字符串为空", -1);
        }
        base64Str = base64Str.replaceAll("data:image/jpeg;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] imgByte = decoder.decodeBuffer(base64Str);
            for (int i = 0; i < imgByte.length; ++i) {
                if (imgByte[i] < 0) {// 调整异常数据
                    imgByte[i] += 256;
                }
            }
            InputStream is = new ByteArrayInputStream(imgByte);
            // 生成jpeg图片
            String fileName = new String((UUID.randomUUID().toString().replace("-", "") + ".jpg").getBytes("gb2312"), "ISO8859-1");
            // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
            GridFSFile gridFSFile = gridFsTemplate.store(is, fileName, "image/jpeg");
            FileInfoAO fileInfo = new FileInfoAO();
            fileInfo.setFileName(fileName);
            fileInfo.setContentType("image/jpeg");
            fileInfo.setMongoFileId(gridFSFile.getId().toString());
            return ServiceResultHelper.genResultWithSuccess(fileInfo);
        } catch (Exception e) {
            return ServiceResultHelper.genResultWithFaild("图片上传失败", -1);
        }
    }
}

6.dubbo服务提供者配置:

ssbService.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ssb="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
 
    <!-- 服务信息,用于计算依赖关系 -->
    <ssb:application name="file-service"/>
 
    <!-- 使用Zookeeper注册中心 -->
    <ssb:registry address="${dubbo.registry.address}" timeout="60000"/>
    <ssb:protocol name="dubbo"  port="-1" />

</beans>

ssbProvider.xml: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ssb="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://code.alibabatech.com/schema/dubbo
       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!-- 声明需要暴露的服务接口 -->
    <ssb:service interface="com.jp.common.file.service.IFileInfoService" ref="fileInfoService" />
    <ssb:service interface="com.jp.common.file.service.IFileService" ref="fileService" />
</beans>

7.springboot启动类:

@ImportResource({"classpath:conf/*.xml" }) 扫描提供者xml配置   
MapperScan("com.jp.common.file.provider.dao") 扫描mapper配置
package com.jp.common.file.provider;

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


@SpringBootApplication
@ComponentScan({"com.jp.framework","com.jp.common.file.provider"})
@MapperScan("com.jp.common.file.provider.dao")
@ImportResource({"classpath:conf/*.xml" })
public class FileProviderApplication {

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

}

服务端启动:

服务注册成功。 

项目源码下载地址:https://github.com/yangfeng005/springboot-dubbo-file-service

三、服务消费者

项目目录结构如下:

1.新建maven工程zpzc_ms,pom.xml文件加入服务端打包的共有模块file-api,加入dubbo依赖:

        <dependency>
            <artifactId>file_api</artifactId>
            <groupId>com.jp.common</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.5.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.1</version>
        </dependency>

2.新建springboot模块zpzc-web,dubbo配置文件ssbService.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
 
    <!-- 服务信息,用于计算依赖关系 -->
    <dubbo:application name="zpzc-srv" />

    <!-- 使用Zookeeper注册中心 -->
    <dubbo:registry address="zookeeper://192.168.2.185:2181" timeout="60000"/>

    <dubbo:protocol name="dubbo" port="-1" dispather="all"/>
    <!-- 用dubbo协议在20880端口暴露服务 -->
    <dubbo:consumer check="false" />

    <dubbo:reference id="fileInfoService" interface="com.jp.common.file.service.IFileInfoService" />
    <dubbo:reference id="fileService" interface="com.jp.common.file.service.IFileService" />
   
</beans>

3.springboot 启动配置:

package com.jp.zpzc;

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


@MapperScan("com.jp.zpzc.dao")
@ComponentScan({"com.jp.framework","com.jp.zpzc."})
@ImportResource({"classpath:conf/*.xml"})
@SpringBootApplication
public class Application {

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

 4.controller:调用文件服务

package com.jp.zpzc.controller.file;

import com.jp.common.file.service.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 文件上传 
 *
 * @author yangfeng
 * @date 2018-06-04 12:57
 **/
@Controller
@RequestMapping("/file")
public class FileController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private IFileService fileService;


    /**
     * base64字符串图片上传
     *
     * @param base64Str
     * @return
     */
    @RequestMapping(value = "/base64StrUpload", method = RequestMethod.POST)
    @ResponseBody
    public Object base64StrUpload(String base64Str) {
        return fileService.base64StrUpload(base64Str);
    }

}

5.消费端启动结果:

6.postman接口调用测试:

猜你喜欢

转载自blog.csdn.net/xiaoxiangzi520/article/details/85597378