使用Echarts和Ajax动态加载数据进行大数据可视化

来源:互联网 发布:wps数据透视表高级技巧 编辑:程序博客网 时间:2024/05/21 10:46

在前面的帖子【Java/Web调用Hadoop进行MapReduce示例】中,我们实现了JavaWeb调用Hadoop统计用户上传的文本文件中的单词出现的次数。

效果如下:

现在我们使用Echarts进行数据可视化,达到如下目的:




二、服务器端的改动

相比之前,服务器端改用json返回数据,将排过序的map返回,key为单词,value为该单词出现的次数。

@RequestMapping("/wordcount")//调用Hadoop进行mapreducepublic void wordcount(HttpServletRequest request,HttpServletResponse response) {Map<String,Integer> tempMap = new HashMap<String,Integer>();List<String> strlist= new ArrayList<String>();System.out.println("进入controller wordcount ");User user = (User) request.getSession().getAttribute("user");System.out.println(user);// if(user == null)// return "login";WordCount c = new WordCount();//新建单词统计任务String username = user.getU_username();String input = "hdfs://chenjie-virtual-machine:9000/user/" + username+ "/wordcountinput";//指定Hadoop文件系统的输入文件夹String output = "hdfs://chenjie-virtual-machine:9000/user/" + username+ "/wordcountoutput";//指定Hadoop文件系统的输出文件夹String reslt = output + "/part-r-00000";//默认输出文件try {Thread.sleep(3*1000);c.main(new String[] { input, output });//调用单词统计任务Configuration conf = new Configuration();//新建Hadoop配置conf.addResource(new Path("/opt/hadoop-1.2.1/conf/core-site.xml"));//添加Hadoop配置,找到Hadoop部署信息conf.addResource(new Path("/opt/hadoop-1.2.1/conf/hdfs-site.xml"));//Hadoop配置,找到文件系统FileSystem fileSystem = FileSystem.get(conf);//得打文件系统Path file = new Path(reslt);//找到输出结果文件FSDataInputStream inStream = fileSystem.open(file);//打开URI uri = file.toUri();//得到输出文件路径System.out.println(uri);String data = null;while ((data = inStream.readLine()) != null ) {strlist.add(data);int bt = data.lastIndexOf('\t');//Hadoop的输出文件每一行为word   times的形式,单词和次数之间为一个tab键(\t)tempMap.put(data.substring(0,bt), Integer.parseInt(data.substring(bt+1,data.length())));//System.out.println(data.substring(0,bt) + "出现了" + Integer.parseInt(data.substring(bt+1,data.length())) + "次");//response.getOutputStream().println(data);//讲结果文件写回用户网页}//response.getOutputStream().println("success.");//讲结果文件写回用户网页inStream.close();tempMap = sortByValue(tempMap);//将该Map按出现次数从大到小排序Map<String,Integer> resultMap = new HashMap<String,Integer>();Set<String> keys = tempMap.keySet();int size = 50;//找到前20个for(String key : keys){if(size==0)break;resultMap.put(key, tempMap.get(key));size--;}Gson gson = new Gson();String json  = gson.toJson(resultMap);//将结果转化为json字符串request.getSession().setAttribute("json", json);//存入session中response.getWriter().write(json);//返回json字符串} catch (Exception e) {System.err.println(e.getMessage());e.printStackTrace();}}public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {            @Override            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {                return (o2.getValue()).compareTo(o1.getValue());//从大到小            }        });        Map<K, V> result = new LinkedHashMap<>();        for (Map.Entry<K, V> entry : list) {            result.put(entry.getKey(), entry.getValue());        }        return result;    }



三、前端

1、ajax从后台获得数据:

function getResult()  {      //alert(dataURL);//http://192.168.153.128:8080/CJHadoopOnline/hadoop/wordcountResult      $.ajax({          type: "POST",          url:"hadoop/wordcountResult",          async:false,          success:function(map){            alert(map);                //处理得到的json数据          }      });  }</script>


2、Echarts柱状图画法


  <script type="text/javascript">function getResult()  {      //alert(dataURL);//http://192.168.153.128:8080/CJHadoopOnline/hadoop/wordcountResult      $.ajax({          type: "POST",          url:"hadoop/wordcountResult",          async:false,          success:function(map){            alert(map);                       var jsonobj=eval('('+map+')');//将json字符串转为json对象                        var keys = new Array();//新建一个数组保存所有的key            var values = new Array();//新建一个数组保存所有的value            for(var key in jsonobj)            {            keys.push(key);            values.push(jsonobj[key]);//sonobj[key]为key对应的value            }                        var myChart = echarts.init(document.getElementById('main'));         // 显示标题,图例和空的坐标轴         myChart.setOption({             title: {                 text: 'Hadoop处理的词频统计'             },             tooltip: {},             legend: {                 data:['出现次数']             },             xAxis: {                 data: []             },             yAxis: {},             series: [{                 name: '出现次数',                 type: 'bar',                 data: []             }]         });                     myChart.setOption({             xAxis: {                 data: keys             },             series: [{                 // 根据名字对应到相应的系列                 name: '出现次数',                 data: values             }]         });                                  }      });  }</script>

3、Echarts字符云画法

function getResult()  {      //alert(dataURL);//http://192.168.153.128:8080/CJHadoopOnline/hadoop/wordcountResult      $.ajax({          type: "POST",          url:"hadoop/wordcountResult",          async:false,          success:function(map){            alert(map);                       var jsonobj=eval('('+map+')');//将json字符串转换为json对象                       var items = new Array();//新建一个对象数组,从官方静态事例data: [{},{},{}]看出数据是一个对象数组                  for(var key in jsonobj)            {            var item = new Object(); //新建一个对象            item.name = key;//该对象的name属性值为key            item.value = jsonobj[key];//该对象的value属性值为jsonobj[key];            items.push(item);            }               var chart = echarts.init(document.getElementById('main'));            var option = {                tooltip: {},                series: [ {                    type: 'wordCloud',                    gridSize: 2,                    sizeRange: [12, 50],                    rotationRange: [-90, 90],                    shape: 'pentagon',                    width: 600,                    height: 400,                    drawOutOfBound: true,                    textStyle: {                        normal: {                            color: function () {                                return 'rgb(' + [                                    Math.round(Math.random() * 160),                                    Math.round(Math.random() * 160),                                    Math.round(Math.random() * 160)                                ].join(',') + ')';                            }                        },                        emphasis: {                            shadowBlur: 10,                            shadowColor: '#333'                        }                    },                                        data:items                    /*                     data: [                        {                            name: '词云',                            value: 10000,                            textStyle: {                                normal: {                                    color: 'black'                                },                                emphasis: {                                    color: 'red'                                }                            }                        },                        {                            name: '云计算',                            value: 555                        },                        {                            name: '人工智能',                            value: 550                        }                    ]                    */                                   } ]            };            chart.setOption(option);            window.onresize = chart.resize;                }      });  }</script>

源代码:

https://github.com/tudoupaisimalingshu/CJHadoopOnline