:大数据行业部署实战3:基于Hadoop的Web版的云盘

本文涉及的产品
云原生大数据计算服务MaxCompute,500CU*H 100GB 3个月
云原生大数据计算服务 MaxCompute,5000CU*H 100GB 3个月
简介: :大数据行业部署实战3:基于Hadoop的Web版的云盘

一、实验目的

熟练采用JAVA API访问 HDFS。

二、实验原理

HDFS是hadoop平台的核心组成之一。熟悉使用hadoop平台需要熟练访问HDFS。HDFS的访问方式有多种。可通过web访问,也可通过shell方式或者API方式访问。基本操作有对文件的读、写、追加、删除等。新建文件夹、删除文件夹等。还可显示文件及文件夹的属性。

HDFS主要用到了FileSystem类,相关的接口可以在这里查到:

http://hadoop.apache.org/docs/r2.7.3/api/org/apache/hadoop/fs/FileSystem.html

或通过IDEA,Ctrl+点击 FileSystem类,也可以看到源码。

下面列了FileSystem的常用接口:

三、实验环境

hadoop2.7.3

Java IDE:IDEA

四、实验内容

打开桌面terminal,在家目录下,下载项目,并解压缩

wget http://i9000.net:8888/sgn/HUP/HadoopDeployPro/cloud-disk.zip
unzip cloud-disk.zip

检查是否已启动Hadoop

用jps查看是否启动成功,如果有进程未启动,可以尝试再次启动Hadoop

1.打开IDEA,导入项目“clouddisk”。

选择clouddisk项目的pom.xml

2.修改配置

application.properties文件中修改下面的IP为虚拟机的IP,此时我们写localhost即可

hadoop.namenode.rpc.url=hdfs://localhost:8020

3.修改用户代码观察网盘效果

将如图文件的,将所有的hadoop用户改为ubuntu,涉及创建目录、删除目录等,总共5处需要修改。

4.右键运行

当看到如下截图时:

访问页面:

http://localhost:9090/ (链接到外部网站。)链接到外部网站。

可以看到实验一、实验二在hdfs上的目录,我们还可以自己创建,删除,重命名

无论删除还是增加都会有日志:

NOTE:每一次修改代码都需要重新运行代码,点击如图Rerun图标,重新运行代码,当tomcat与项目代码都启动时,打开浏览器再进行操作

5.开发,实现上传、下载

类名:com.mypro.clouddisk.hdfs.FileSystemImpl

实现upload 、download的代码。

@Override
public void upload(InputStream is, String dstHDFSFile) throws Exception {
//TODO
//代码待实现
System.out.println( "Upload Successfully!" );
}
@Override
public void download(String file, OutputStream os) throws Exception {
//TODO
//代码待实现
System.out.println( "Download Successfully!" );
}

五、代码附录

IndexController

package com.mypro.clouddisk.controller;
import com.mypro.clouddisk.hdfs.IFileSystem;
import com.mypro.clouddisk.model.FileIndex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@Controller
public class IndexController {
    @Autowired
    private IFileSystem fileSystem = null;
    @RequestMapping("/")
    public String index(String path,Model model) {
        FileIndex fileIndex = new FileIndex();
        path = (path==null || path.trim().isEmpty()) ? "/": path.trim();
        fileIndex.setPath(path);
        String fileName = fileSystem.getFileName(path);
        fileIndex.setName(fileName);
        model.addAttribute("rootDir",fileIndex);
        List<FileIndex> list = new ArrayList<FileIndex>();
        try {
            list = fileSystem.ls(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("rootFiles",list);
        return "index";
    }
    @GetMapping("/download")
    public String download(HttpServletResponse response, @RequestParam String file) throws Exception {
//        String filename="xxx.txt";
        File hFile = new File(file);
        String filename = hFile.getName();
        response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
        fileSystem.download(file,response.getOutputStream());
        return null;
    }
    /**
     *
     * @param path  //???????
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public String delete(@RequestParam String path) throws Exception {
        String parentPath = fileSystem.rm(path);
        //??????
        return "redirect:./?path=" + parentPath;
    }
    @ResponseBody
    @RequestMapping(value="/checkMD5",method=RequestMethod.POST)
    public String checkMD5(String md5code){
        //??????????MD5??md5code???
        return "no";
    }
    @PostMapping("/uploadFile")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   String parentPath,RedirectAttributes redirectAttributes) throws IOException {
        String fileName = getOriginalFilename(file.getOriginalFilename());
        InputStream is = file.getInputStream();
        Long size = file.getSize();
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }
        try {
            String dstPath = parentPath.endsWith("/")? (parentPath+fileName) : (parentPath +"/"+fileName);
            fileSystem.upload(is,dstPath);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:./?path="+parentPath;
    }
    @PostMapping("/mkdir")
    public String mkdir(String directName,String parentPath) throws Exception {
        String newDir = parentPath.endsWith("/")?(parentPath+directName):(parentPath+"/"+directName);
        fileSystem.mkdir(newDir);
        return "redirect:./?path="+parentPath;
    }
    @RequestMapping("renameForm")
    public String renameForm(String directName,String isRoot,String path) throws Exception {
        //??fileindex?name?path
        //???????path
        String[] arr= fileSystem.rename(path,directName);
        //?????????????????????????????????????????????????????????
        if(isRoot!=null && isRoot.equals("yes")){
            return "redirect:./?path=" + arr[1];  //mypath
        }else{
            return "redirect:./?path=" + arr[0];//parent
        }
    }
    @RequestMapping("/getOptionalPath")
    @ResponseBody
    public List getOptionalPath(String path){
        //?????fileIndexId?????????????????????????????
        List result =  fileSystem.getOptionTranPath(path);
        return result;
    }
    @RequestMapping("/searchFiles")
    public String searchFiles(String keyWord,@RequestParam(value="pageNum",defaultValue="1")int pageNum,Model model) throws Exception {
        int pageSize = 3;
        List<FileIndex> result = fileSystem.searchFileByPage(keyWord,pageSize,pageNum);
        com.github.pagehelper.Page<FileIndex> page =new com.github.pagehelper.Page<FileIndex>();
        page.addAll(result);
        model.addAttribute("result", page);
        model.addAttribute("keyWord",keyWord);
        return "searchResult";
    }
    @RequestMapping("/stasticFiles")
    public String stasticFiles(Model model){
//        List staticResult = fileSystem.getStaticNums();
        List<Map> staticResult = new ArrayList<Map>();
        Map map = new HashMap();
        map.put("doc_number",100);
        map.put("video_number",87);
        map.put("pic_number",66);
        map.put("code_number",44);
        map.put("other_number",23);
        staticResult.add(map);
        model.addAttribute("staticResult", staticResult);
        return "stasticfiles";
    }
    private String getOriginalFilename(String originalFilename){
        if(originalFilename == null)
        {
            return "";
        }
        if(originalFilename.contains("/") || originalFilename.contains("\\")){
            File file = new File(originalFilename);
            return file.getName();
        }
        return  originalFilename;
    }
}
}

FileSystemImpl

package com.mypro.clouddisk.hdfs;
import com.mypro.clouddisk.model.FileIndex;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Component
public class FileSystemImpl implements IFileSystem {
    Logger logger = LoggerFactory.getLogger(FileSystemImpl.class);
    @Value("${hadoop.namenode.rpc.url}")
    private String namenodeRpcUrl;
//    private static String NAMENODE_RPC="hdfs://192.168.72.128:8020";
    @Override
    public List<FileIndex> ls(String dir) throws Exception{
        Configuration conf=new Configuration();
        //??NameNode??
        URI uri=new URI(namenodeRpcUrl);
        //?????,??FileSystem??
        FileSystem fs=FileSystem.get(uri,conf,"ubuntu");
        Path path = new Path(dir);
        //????????
        if(! fs.exists(path)){
            logger.error("dir:"+dir+" not exists!");
            throw new RuntimeException("dir:"+dir+" not exists!");
        }
        List<FileIndex> list = new ArrayList<FileIndex>();
        FileStatus[] filesStatus = fs.listStatus(path);
        for(FileStatus f:filesStatus){
            FileIndex fileIndex = new FileIndex();
            fileIndex.setIsFile(f.isDirectory()?"0":"1");
            fileIndex.setName(f.getPath().getName());
            fileIndex.setPath(f.getPath().toUri().getPath());
            fileIndex.setCreateTime(new Date());
            list.add(fileIndex);
        }
        //??????FileSystem????
        fs.close();
        return list;
    }
    @Override
    public void mkdir(String dir) throws Exception{
        Configuration conf=new Configuration();
        //??NameNode??
        URI uri=new URI(namenodeRpcUrl);
        //?????,??FileSystem??
        FileSystem fs=FileSystem.get(uri,conf,"ubuntu");
        fs.mkdirs(new Path(dir));
        //??????FileSystem????client
        fs.close();
        System.out.println( "mkdir "+dir+" Successfully!" );
    }
    @Override
    /**
     * ???????
     */
    public String rm(String path) throws Exception {
        Configuration conf=new Configuration();
        //??NameNode??
        URI uri=new URI(namenodeRpcUrl);
        //?????,??FileSystem??
        FileSystem fs=FileSystem.get(uri,conf,"ubuntu");
        Path filePath = new Path(path);
        fs.delete(filePath,true);
        //??????FileSystem????client
        fs.close();
        System.out.println( "Delete "+path+" Successfully!" );
        return filePath.getParent().toUri().getPath();
    }
    @Override
    public void upload(InputStream is, String dstHDFSFile) throws Exception {
        //TODO
    //???
        System.out.println( "Upload Successfully!" );
    }
    @Override
    public void download(String file, OutputStream os) throws Exception {
            //TODO
    //???
        System.out.println( "Download Successfully!" );
    }
    @Override
    public void mv() {
    }
    @Override
    public String[] rename(String path, String dirName) throws Exception {
        Configuration conf=new Configuration();
        //??NameNode??
        URI uri=new URI(namenodeRpcUrl);
        //?????,??FileSystem??
        FileSystem fs=FileSystem.get(uri,conf,"ubuntu");
        Path oldPath = new Path(path);
        if(oldPath.getParent() ==null){
            String[] arr = new String[2];
            arr[0]="/";
            arr[1]="/";
            return arr;
        }
        String parentPath = oldPath.getParent().toUri().getPath();
        String newPathStr = parentPath.endsWith("/")?(parentPath+dirName):(parentPath + "/" +dirName);
        Path newPath = new Path(newPathStr );
        fs.rename(oldPath,newPath);
        //??????FileSystem????client
        fs.close();
        String[] arr = new String[2];
        arr[0]=parentPath;
        arr[1]=newPathStr;
        System.out.println( "rename Successfully!" );
        return arr;
    }
    @Override
    public String getFileName(String path) {
        Path filePath = new Path(path);
        return filePath.getName();
    }
    @Override
    public List getOptionTranPath(String path) {
        return new ArrayList();
    }
    @Override
    public List<FileIndex> searchFileByPage(String keyWord, int pageSize, int pageNum) throws Exception{
        Configuration conf=new Configuration();
        //??NameNode??
        URI uri=new URI(namenodeRpcUrl);
        //?????,??FileSystem??
        FileSystem fs=FileSystem.get(uri,conf,"ubuntu");
        ArrayList<FileStatus> results = null;
        PathFilter filter = new PathFilter() {
            @Override
            public boolean accept(Path path) {
                if(keyWord == null || keyWord.trim().isEmpty()){
                    return false;
                }
                if(path.getName().contains(keyWord)){
                    return  true;
                }
                return false;
            }
        };
        List<FileIndex> list = new ArrayList<FileIndex>();
        FileStatus[] fileStatusArr = fs.listStatus(new Path("/"),filter);
        for(FileStatus status :fileStatusArr){
            FileIndex fileIndex = new FileIndex();
            fileIndex.setPath(status.getPath().toUri().getPath());
            fileIndex.setName(status.getPath().getName());
            fileIndex.setIsFile(status.isFile()?"1":"0");
            list.add(fileIndex);
        }
        //??????FileSystem????client
        fs.close();
        System.out.println( "Search Successfully!" );
        return list;
    }
    @Override
    public List getStaticNums() {
        return null;
    }
}

FileSystem

package com.mypro.clouddisk.hdfs;
import com.mypro.clouddisk.model.FileIndex;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.List;
public interface IFileSystem {
    /**
     * ls ????????
     * @return
     */
    List<FileIndex> ls(String dir) throws Exception;
    /**
     * ????
     * @return
     */
    void mkdir(String dir)throws Exception;
    /**
     * ???????
     * ??????
     */
    String rm(String path) throws Exception;
    /**
     * ??
     */
    void upload(InputStream is, String dstHDFSFile) throws Exception;
    /**
     * ??
     */
    void download(String file, OutputStream os) throws Exception;
    /**
     * ???
     */
    void mv();
    /**
     * ???
     */
    String[] rename(String path,String dirName) throws Exception;
    /**
     * ?????
     * @param path
     * @return
     */
    String getFileName(String path);
    //?????fileIndexId?????????????????????????????
    List getOptionTranPath(String path);
    List<FileIndex> searchFileByPage(String keyWord, int pageSize, int pageNum) throws Exception;
    List getStaticNums();
}


相关实践学习
基于MaxCompute的热门话题分析
本实验围绕社交用户发布的文章做了详尽的分析,通过分析能得到用户群体年龄分布,性别分布,地理位置分布,以及热门话题的热度。
SaaS 模式云数据仓库必修课
本课程由阿里云开发者社区和阿里云大数据团队共同出品,是SaaS模式云原生数据仓库领导者MaxCompute核心课程。本课程由阿里云资深产品和技术专家们从概念到方法,从场景到实践,体系化的将阿里巴巴飞天大数据平台10多年的经过验证的方法与实践深入浅出的讲给开发者们。帮助大数据开发者快速了解并掌握SaaS模式的云原生的数据仓库,助力开发者学习了解先进的技术栈,并能在实际业务中敏捷的进行大数据分析,赋能企业业务。 通过本课程可以了解SaaS模式云原生数据仓库领导者MaxCompute核心功能及典型适用场景,可应用MaxCompute实现数仓搭建,快速进行大数据分析。适合大数据工程师、大数据分析师 大量数据需要处理、存储和管理,需要搭建数据仓库?学它! 没有足够人员和经验来运维大数据平台,不想自建IDC买机器,需要免运维的大数据平台?会SQL就等于会大数据?学它! 想知道大数据用得对不对,想用更少的钱得到持续演进的数仓能力?获得极致弹性的计算资源和更好的性能,以及持续保护数据安全的生产环境?学它! 想要获得灵活的分析能力,快速洞察数据规律特征?想要兼得数据湖的灵活性与数据仓库的成长性?学它! 出品人:阿里云大数据产品及研发团队专家 产品 MaxCompute 官网 https://www.aliyun.com/product/odps&nbsp;
目录
相关文章
|
1天前
|
SQL 安全 数据库
Python Web开发者必学:SQL注入、XSS、CSRF攻击与防御实战演练!
【7月更文挑战第26天】在 Python Web 开发中, 安全性至关重要。本文聚焦 SQL 注入、XSS 和 CSRF 这三大安全威胁,提供实战防御策略。SQL 注入可通过参数化查询和 ORM 框架来防范;XSS 则需 HTML 转义用户输入与实施 CSP;CSRF 防御依赖 CSRF 令牌和双重提交 Cookie。掌握这些技巧,能有效加固 Web 应用的安全防线。安全是持续的过程,需贯穿开发始终。
6 1
Python Web开发者必学:SQL注入、XSS、CSRF攻击与防御实战演练!
|
12天前
|
数据库 开发者 Python
实战指南:用Python协程与异步函数优化高性能Web应用
【7月更文挑战第15天】Python的协程与异步函数优化Web性能,通过非阻塞I/O提升并发处理能力。使用aiohttp库构建异步服务器,示例代码展示如何处理GET请求。异步处理减少资源消耗,提高响应速度和吞吐量,适用于高并发场景。掌握这项技术对提升Web应用性能至关重要。
37 10
|
14天前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
【7月更文挑战第13天】在Web开发中,AJAX和Fetch API是实现页面无刷新数据交换的关键。在Flask博客系统中,通过创建获取评论的GET路由,我们可以展示使用AJAX和Fetch API的前端实现。AJAX通过XMLHttpRequest发送请求,处理响应并在成功时更新DOM。Fetch API则使用Promise简化异步操作,代码更现代。这两个工具都能实现不刷新页面查看评论,Fetch API的语法更简洁,错误处理更直观。掌握这些技巧能提升Python Web项目的用户体验和开发效率。
26 7
|
10天前
|
前端开发 JavaScript UED
Python Web应用中的WebSocket实战:前后端分离时代的实时数据交换
【7月更文挑战第16天】在前后端分离的Web开发中,WebSocket解决了实时数据交换的问题。使用Python的Flask和Flask-SocketIO库,后端创建WebSocket服务,监听并广播消息。前端HTML通过JavaScript连接到服务器,发送并显示接收到的消息。WebSocket适用于实时通知、在线游戏等场景,提升应用的实时性和用户体验。通过实战案例,展示了如何实现这一功能。
|
5天前
|
存储 JSON API
实战派教程!Python Web开发中RESTful API的设计哲学与实现技巧,一网打尽!
【7月更文挑战第22天】构建RESTful API实战:**使用Python Flask设计图书管理API,遵循REST原则,通过GET/POST/PUT/DELETE操作处理/books及/books/&lt;id&gt;。示例代码展示资源定义、请求响应交互。关键点包括HTTP状态码的使用、版本控制、错误处理和文档化。本文深入探讨设计哲学与实现技巧,助力理解RESTful API开发。
16 0
|
6天前
|
缓存 中间件 网络架构
Python Web开发实战:高效利用路由与中间件提升应用性能
【7月更文挑战第20天】在Python Web开发中,路由与中间件是构建高效应用的核心。路由通过装饰器如`@app.route()`在Flask中映射请求至处理函数;中间件(如`@app.before_request`, `@app.after_request`)则在请求流程中插入自定义逻辑。优化路由包括减少冲突、利用动态参数及蓝图;中间件可用于缓存响应、请求验证和异常处理,显著提升性能和可维护性。良好设计是关键,示例代码展示了如何在Flask中实现这些策略。
20 0
|
19天前
|
移动开发 前端开发 JavaScript
Web表单(Form)开发实战指南
【7月更文挑战第8天】表单(Form)是Web应用程序中不可或缺的组成部分,用于收集用户输入的数据。本指南将详细介绍HTML表单的基本结构、数据提交方式、表单验证以及如何使用JavaScript和CSS增强表单的交互性和美观性。
50 0
|
21天前
|
运维 监控 大数据
部署-Linux01,后端开发,运维开发,大数据开发,测试开发,后端软件,大数据系统,运维监控,测试程序,网页服务都要在Linux中进行部署
部署-Linux01,后端开发,运维开发,大数据开发,测试开发,后端软件,大数据系统,运维监控,测试程序,网页服务都要在Linux中进行部署
|
25天前
|
分布式计算 Hadoop 大数据
优化大数据处理:Java与Hadoop生态系统集成
优化大数据处理:Java与Hadoop生态系统集成