首页 文章 精选 留言 我的

精选列表

搜索[消息API],共10000篇文章
优秀的个人博客,低调大师

Building a Keras + deep learning REST API(三部曲之一)

一、基本环境 $ pip install flask gevent requests pillow 其中 flask不需要解释 gevent 是用于自动切换进程的; pillow 是用来进行python下的图像处理的; requests 是用来进行python下request处理的。 二、核心代码解释 # import the necessary packages from keras.applications import ResNet50 from keras.preprocessing.image import img_to_array from keras.applications import imagenet_utils from PIL import Image import numpy as np import flask import io 引入所需的头文件。其中注意keras的几个类库是很有通用性的; # initialize our Flask application and the Keras model app = flask.Flask( __name__) model = None 类库的初始化 def load_model(): # load the pre-trained Keras model (here we are using a model # pre-trained on ImageNet and provided by Keras, but you can # substitute in your own networks just as easily) global model model = ResNet50( weights= "imagenet") 引入model模型,如果想引入自己的模型(CBIR)的话,就在这里引入。 def prepare_image( image, target): # if the image mode is not RGB, convert it if image.mode != "RGB": image = image.convert( "RGB") # resize the input image and preprocess it image = image.resize(target) image = img_to_array(image) image = np.expand_dims(image, axis= 0) image = imagenet_utils.preprocess_input(image) # return the processed image return image image的预处理,这里使用的是keras+PIL,和opencv之间的比较,需要有时间来做。 @app.route( "/predict", methods=[ "POST"]) def predict(): # initialize the data dictionary that will be returned from the # view data = { "success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get( "image"): # read the image in PIL format image = flask.request.files[ "image"].read() image = Image.open(io.BytesIO(image)) # preprocess the image and prepare it for classification image = prepare_image(image, target=( 224, 224)) # classify the input image and then initialize the list # of predictions to return to the client preds = model.predict(image) results = imagenet_utils.decode_predictions(preds) data[ "predictions"] = [] # loop over the results and add them to the list of # returned predictions for (imagenetID, label, prob) in results[ 0]: r = { "label": label, "probability": float(prob)} data[ "predictions"].append(r) # indicate that the request was a success data[ "success"] = True # return the data dictionary as a JSON response return flask.jsonify(data) 虽然是核心部分,但是其实非常容易被复用。就是读取数据,然后进行处理的过程。 # if this is the main thread of execution first load the model and # then start the server if __name__ == "__main__": print(( "* Loading Keras model and Flask starting server..." "please wait until server has fully started")) load_model() app.run() 比不可少的main过程。缺少不可运行。 三、运行效果 使用VPS能够更快地得到效果,至少你不需要下载resnet*.h5,一个链路不是太好的大物件。 flask的运行效果,使用curl进行处理的效果 从结果上来看,curch排在了第2,而将这张图片识别为钟楼或者修道院、城堡,宫殿 ,似乎也没有什么不妥。 四、小结反思 真的仅仅是通过了几行代码,就实现了flask部署的核心问题。不过光是跑这个简单的过程,机器就已经发出巨大的热量了;另一方面,整个的结构是什么,也需要进一步去研究清楚才对。 来自为知笔记(Wiz) 目前方向:图像拼接融合、图像识别 联系方式:jsxyhelu@foxmail.com

优秀的个人博客,低调大师

Java高并发秒杀Api-业务分析与DAO层构建3

章节目录 mybatis与spring整合过程 spring-dao.xml 配置 junit4 单元测试 1.mybatis与spring整合过程 1.1 spring-dao.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置整合mybatis--> <!--1:配置数据库相关参数--> <!-- 1:配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.数据库连接池配置--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性--> <property name="driverClass" value="${driver}" /> <property name="jdbcUrl" value="${url}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!-- c3p0连接池的私有属性--> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit--> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 30个连接用完--> <property name="checkoutTimeout" value="1000" /> <!-- 当获取连接失败重试次数--> <property name="acquireRetryAttempts" value="2" /> </bean> <!-- 约定大于配置--> <!-- 3:配置SqlSessionFactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource" /> <!-- 配置MyBatis全局配置文件:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描entity包 使用别名--> <property name="typeAliasesPackage" value="org.seckill.domain" /> <!-- 扫描sql配置文件;mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!--配置扫描Dao接口包,动态实现Dao接口 mapper 代理,并注入到Spring容器中 MapperScannerConfigurer--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory,懒加载,用到的时候才加载--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!--给出扫描DAO接口包--> <property name="basePackage" value="org.seckill.dao"></property> </bean> </beans> 2.junit 单元测试 SecKillDaoTest.java - 测试秒杀 package org.seckill.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.domain.SecKill; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Date; import java.util.List; /** * 配置spring 与 junit 启动时加载Spring IOC容器 * spring-test,junit整合 * 告诉junit Spring配置文件位置 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-dao.xml"}) public class SecKillDaoTest { //注入Dao类实现 @Autowired private SecKillDao secKillDao; @Test public void queryById() throws Exception { long id = 1000; SecKill secKill = secKillDao.queryById(id); System.out.println(secKill.getName()); System.out.println(secKill); /** * 1000元秒杀iphone x SecKill{seckillId=1000, name='1000元秒杀iphone x', stock=100, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018 } */ } /** * @throws Exception */ @Test public void queryAll() throws Exception { // queryAll(offset,limit)->queryAll(arg0,arg1) List<SecKill> secKillList = secKillDao.queryAll(0, 100); for (SecKill secKill : secKillList) { System.out.println(secKill); } /** * SecKill{seckillId=1000, name='1000元秒杀iphone x', stock=100, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1001, name='500元秒杀ipad x', stock=200, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1002, name='300元秒杀小米4', stock=300, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1003, name='200元秒杀小米note', stock=400, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} */ } @Test public void reduceStock() throws Exception { Date killTime = new Date(); int updateCount = secKillDao.reduceStock(1000L, killTime); System.out.println(updateCount); } } 测试秒杀明细 package org.seckill.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.domain.SuccessKilled; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-dao.xml") public class SuccessKilledDaoTest { @Autowired private SuccessKilledDao successKilledDao; @Test public void insertSuccessKilled() throws Exception { int successCount = successKilledDao.insertSuccessKilled(1001L, "15300815999"); System.out.println("insertCount=" + successCount); } @Test public void queryByIdWithSecKill() throws Exception { //1个用户只能查询到属于自己的一个秒杀明细 long id = 1001L; String phone = "15300815999"; SuccessKilled successKilled = successKilledDao.queryByIdWithSecKill(id, phone); System.out.println(successKilled); } } 接下来是service 层的构建

优秀的个人博客,低调大师

Java高并发秒杀Api-业务分析与DAO层构建1

章节目录 1.为什么使用Spring+Spring MVC+Mybatis 2.秒杀业务特性 3.秒杀分析过程、优化思路 4.相关技术介绍 5.基于Maven创建项目 6.秒杀业务分析 7.秒杀事务的难点分析 8.实现秒杀的哪些功能 1.为什么使用Spring+Spring MVC+Mybatis 框架易于使用、轻量级 对业务代码侵入性低 成熟的社区与资料 2.秒杀业务特性 秒杀业务场景具有典型的"事务"特性 秒杀、红包类需求越来越常见,对竞争资源的访问 面试常问的问题 3.相关技术介绍 MySQL 表设计 SQL技巧 事务、行级锁 MyBatis DAO层设计与开发 MyBatis 合理使用 MyBatis 与 Spring整合 Spring Spring Ioc 整合Service Spring 声明式事务使用 Spring MVC Restful 接口设计与使用 框架运作流程 Controller 设计技巧 前端 交互设计 BootStrap Jquery 高并发 高并发点和高并发分析 优化思路并实现 4.基于Maven创建项目 1.maven命令创建web项目骨架 mvn archetype:generate -DgroupId=org.seckill -DartifactId=seckill - DarchetypeArtifactId=maven-archetype-webapp 5.秒杀业务分析 如下图所示: 秒杀业务系统流程分析 所以秒杀业务的核心是对库存的处理。 用户针对库存处理的业务分析用户的秒杀过程 需要减库存->记录购买明细->组成完整事务->数据持久化 如下图所示: 用户秒杀过程 用户购买行为 记录谁购买成功了->成功的时间及有效期->付款、发货信息 为什么需要事务 事务不完整导致的数据一致性问题 如上图所示 1.减了库存,但是没有用户的购买明细,那么就会出现50个商品,但是购买明 细小于50个,到时候发货会发现有些许商品滞留在仓库中,此种情况属于少卖 的情况。 2.记录了明细但是没有减库存,就会发现订单量比商品量要多,出现超卖的情 况,还有一种情况也会导致超卖,多个用户并发修改库存,加入库存量为1,这 个时候多个用户同时去减库存(经过库存量>0的验证),会导致库存为负数, 多个用户抢到同一个商品,这种情况下也会导致超卖发生。 数据落地方案 MySQL VS NoSQL NoSQL非关系型数据库在事务的支持上并没有关系型数据库可靠。 所以归根结底事务机制依然是目前最可靠的落地方案。 6.秒杀事务难点分析 6.1 难点问题-竞争 竞争问题-并发冲突修改 解决方案是采用数据库innodb引擎提供的 事务及 行级锁。 用户减库存的事务流程: begin; update 库存数量; insert 购买明细; commit; 行级锁 如下如所示: 行级锁 情景分析: 在事务执行过程中,mysql默认的repeateable read 隔离级别会在写操作发生的 行上加上行级锁(非记录加锁,而是在对应索引上加锁,上图中的update加锁 发生在id上),多个写请求并发更新同一行记录会产生如下问题: 因为行级锁在事务结束之后才能释放锁,可能会导致锁等待的发生。数据库吞吐率(事务处理能力)会降低。 所以秒杀的难点是什么?秒杀的难点是如何高效的处理竞争-如何在保证数据一致性的情况下高效的处理竞争 8.实现秒杀的哪些功能 1.秒杀接口暴露 浏览器插件获取秒杀接口,通过脚本去秒杀,保护秒杀接口的一种手段。 2.执行秒杀的操作 执行秒杀的业务逻辑 3.秒杀查询,商品详情页查询。 其实市面上最主要的几个秒杀思路是: 1.直接在数据库层面做秒杀 2.缓存中存储库存,用户秒杀请求是将缓存中库存与数据库中库存数据同时进行减库存的过程,保证数据一致性是一个难点。 3.缓存中存储有效的减库存操作,队列减库存的的请求依次顺序执行数据库减库存、生成订单明细事务(操作),如小米。

优秀的个人博客,低调大师

API开创基底细胞癌手术切缘采集,改善过度医疗现状

做为一个医学硕士,曾拥有8年临床医生工作经验,在医院工作时的一件小事让我想明白了一件事:医学应该是个信仰,不该是个职业。 医疗行业对人类这么重要,信息化却这么落后,自己恰好有这方面的能力,也有意愿去提供这样的技术支持。因此我也写了几篇论文,但在我看来没有实际行动的理论,不过就是一堆垃圾。 不经意间的一个机会,开始全心投入医疗技术的研发中,刚开始围绕全套的业务流程有手术预约、数据管理、术后随访,对接了HIS、PACS、LIS,当时医院是内外网分离的,针对多个院区,还做了内外网和异地办公室的数据互通。在当时最大的难点是安装部署,其他医院想使用却用不起来,从院内政策到人员的精力都限制了项目的实施。 其他医院根据业务和使用规模大多需要项目的部分功能,为此不得不将项目拆分,各个模块弹性组合,这样分散式的持续了一段时间,但使用中参与数据录入

优秀的个人博客,低调大师

Hadoop MapReduce编程 API入门系列之压缩和计数器(三十)

生成的结果,作为输入源。 代码 package zhouls.bigdata.myMapReduce.ParseTVDataCompressAndCounter; import java.net.URI; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * * @function 统计无效数据和对输出结果进行压缩 * @author 小讲 * */ public class CompressAndCounter extends Configured implements Tool { // 定义枚举对象 public static enum LOG_PROCESSOR_COUNTER { BAD_RECORDS }; /** * * @function Mapper 解析数据,统计无效数据,并输出有效数据 * */ public static class CompressAndCounterMap extends Mapper<LongWritable, Text, Text, Text> { protected void map(LongWritable key, Text value, Context context) throws java.io.IOException, InterruptedException { // 解析每条机顶盒记录,返回list集合 List<String> list = ParseTVData.transData(value.toString()); //调用ParseTVData.java下的transData方法 int length = list.size(); // 无效记录 if (length == 0) { // 动态自定义计数器 context.getCounter("ErrorRecordCounter", "ERROR_Record_TVData").increment(1); // 枚举声明计数器 context.getCounter(LOG_PROCESSOR_COUNTER.BAD_RECORDS).increment(1); } else { for (String validateRecord : list) { //输出解析数据 context.write(new Text(validateRecord), new Text("")); } } } } /** * @function 任务驱动方法 * */ @Override public int run(String[] args) throws Exception { // TODO Auto-generated method stub //读取配置文件 Configuration conf = new Configuration(); //文件系统接口 URI uri = new URI("hdfs://HadoopMaster:9000"); //输出路径 Path mypath = new Path(args[1]); // 创建FileSystem对象 FileSystem hdfs = FileSystem.get(uri, conf); if (hdfs.isDirectory(mypath)) { //删除已经存在的文件路径 hdfs.delete(mypath, true); } Job job = new Job(conf, "CompressAndCounter");//新建一个任务 job.setJarByClass(CompressAndCounter.class);//设置主类 job.setMapperClass(CompressAndCounterMap.class);//只有 Mapper job.setOutputKeyClass(Text.class);//输出 key 类型 job.setOutputValueClass(Text.class);//输出 value 类型 FileInputFormat.addInputPath(job, new Path(args[0]));//输入路径 FileOutputFormat.setOutputPath(job, new Path(args[1]));//输出路径 FileOutputFormat.setCompressOutput(job, true);//对输出结果设置压缩 FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);//设置压缩类型 job.waitForCompletion(true);//提交任务 return 0; } /** * @function main 方法 * @param args 输入 输出路径 * @throws Exception */ public static void main(String[] args) throws Exception { String[] date = {"20120917","20120918","20120919","20120920","20120921","20120922","20120923"}; int ec = 1; for(String dt:date) { String[] args0 = { "hdfs://HadoopMaster:9000/middle/tv/"+dt+".txt", "hdfs://HadoopMaster:9000/junior/tvCompressResult/"+dt }; // String[] args0 = { "./data/compressAndCounter/"+dt+".txt", // "hdfs://HadoopMaster:9000/junior/tvCompressResult/"+dt }; ec = ToolRunner.run(new Configuration(), new CompressAndCounter(), args0); } System.exit(ec); } } package zhouls.bigdata.myMapReduce.ParseTVDataCompressAndCounter; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @function 解析数据 * * */ public class ParseTVData { /** * @function 使用 Jsoup 工具,解析输入数据, * @param text * @return list */ public static List<String> transData(String text) { List<String> list = new ArrayList<String>(); Document doc; String rec = ""; try { doc = Jsoup.parse(text);// jsoup解析数据 Elements content = doc.getElementsByTag("WIC"); String num = content.get(0).attr("cardNum");// 记录编号 if (num == null || num.equals("")) { num = " "; } String stbNum = content.get(0).attr("stbNum");// 机顶盒号 if (stbNum.equals("")) { return list; } String date = content.get(0).attr("date");// 日期 Elements els = doc.getElementsByTag("A"); if (els.isEmpty()) { return list; } for (Element el : els) { String e = el.attr("e");// 结束时间 String s = el.attr("s");// 开始时间 String sn = el.attr("sn");// 频道名称 rec = stbNum + "@" + date + "@" + sn + "@" + s + "@" + e; list.add(rec); } } catch (Exception e) { System.out.println(e.getMessage()); return list; } return list; } } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6171823.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop MapReduce编程 API入门系列之挖掘气象数据版本3(九)

代码 package zhouls.bigdata.myMapReduce.weather; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableComparable; public class MyKey implements WritableComparable<MyKey>{ //WritableComparable,实现这个方法,要多很多 //readFields是读入,write是写出 private int year; private int month; private double hot; public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public double getHot() { return hot; } public void setHot(double hot) { this.hot = hot; }//这一大段的get和set,可以右键,source,产生get和set,自动生成。 public void readFields(DataInput arg0) throws IOException { //反序列化 this.year=arg0.readInt(); this.month=arg0.readInt(); this.hot=arg0.readDouble(); } public void write(DataOutput arg0) throws IOException { //序列化 arg0.writeInt(year); arg0.writeInt(month); arg0.writeDouble(hot); } //判断对象是否是同一个对象,当该对象作为输出的key public int compareTo(MyKey o) { int r1 =Integer.compare(this.year, o.getYear());//比较当前的年和你传过来的年 if(r1==0){ int r2 =Integer.compare(this.month, o.getMonth()); if(r2==0){ return Double.compare(this.hot, o.getHot()); }else{ return r2; } }else{ return r1; } } } package zhouls.bigdata.myMapReduce.weather; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner; public class MyPartitioner extends HashPartitioner<MyKey, DoubleWritable>{//这里就是洗牌 //执行时间越短越好 public int getPartition(MyKey key, DoubleWritable value, int numReduceTasks) { return (key.getYear()-1949)%numReduceTasks;//对于一个数据集,找到最小,1949 } } //1949-10-01 14:21:02 34c //1949-10-02 14:01:02 36c //1950-01-01 11:21:02 32c //1950-10-01 12:21:02 37c //1951-12-01 12:21:02 23c //1950-10-02 12:21:02 41c //1950-10-03 12:21:02 27c //1951-07-01 12:21:02 45c //1951-07-02 12:21:02 46c //1951-07-03 12:21:03 47c package zhouls.bigdata.myMapReduce.weather; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class MySort extends WritableComparator{ public MySort(){ super(MyKey.class,true);//把MyKey传进了 } public int compare(WritableComparable a, WritableComparable b) {//这是排序的精髓 MyKey k1 =(MyKey) a; MyKey k2 =(MyKey) b; int r1 =Integer.compare(k1.getYear(), k2.getYear()); if(r1==0){//年相同 int r2 =Integer.compare(k1.getMonth(), k2.getMonth()); if(r2==0){//月相同 return -Double.compare(k1.getHot(), k2.getHot());//比较气温 }else{ return r2; } }else{ return r1; } } } package zhouls.bigdata.myMapReduce.weather; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class MyGroup extends WritableComparator{ public MyGroup(){ super(MyKey.class,true);//把MyKey传进了 } public int compare(WritableComparable a, WritableComparable b) {//这是分组的精髓 MyKey k1 =(MyKey) a; MyKey k2 =(MyKey) b; int r1 =Integer.compare(k1.getYear(), k2.getYear()); if(r1==0){ return Integer.compare(k1.getMonth(), k2.getMonth()); }else{ return r1; } } } package zhouls.bigdata.myMapReduce.weather; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class RunJob { // 1949-10-01 14:21:02 34c WeatherMapper // 1949-10-02 14:01:02 36c // 1950-01-01 11:21:02 32c 分区在MyPartitioner.java // 1950-10-01 12:21:02 37c // 1951-12-01 12:21:02 23c 排序在MySort.java // 1950-10-02 12:21:02 41c // 1950-10-03 12:21:02 27c 分组在MyGroup.java // 1951-07-01 12:21:02 45c // 1951-07-02 12:21:02 46c 再,WeatherReducer // 1951-07-03 12:21:03 47c //key:每行第一个隔开符(制表符)左边为key,右边为value 自定义类型MyKey,洗牌, static class WeatherMapper extends Mapper<Text, Text, MyKey, DoubleWritable>{ SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); NullWritable v =NullWritable.get(); // 1949-10-01 14:21:02是自定义类型MyKey,即key // 34c是DoubleWritable,即value protected void map(Text key, Text value,Context context) throws IOException, InterruptedException { try { Date date =sdf.parse(key.toString()); Calendar c =Calendar.getInstance(); //Calendar 类是一个抽象类,可以通过调用 getInstance() 静态方法获取一个 Calendar 对象, //此对象已由当前日期时间初始化,即默认代表当前时间,如 Calendar c = Calendar.getInstance(); c.setTime(date); int year =c.get(Calendar.YEAR); int month =c.get(Calendar.MONTH); double hot =Double.parseDouble(value.toString().substring(0, value.toString().lastIndexOf("c"))); MyKey k =new MyKey(); k.setYear(year); k.setMonth(month); k.setHot(hot); context.write(k, new DoubleWritable(hot)); } catch (Exception e) { e.printStackTrace(); } } } static class WeatherReducer extends Reducer<MyKey, DoubleWritable, Text, NullWritable>{ protected void reduce(MyKey arg0, Iterable<DoubleWritable> arg1,Context arg2)throws IOException, InterruptedException { int i=0; for(DoubleWritable v :arg1){ i++; String msg =arg0.getYear()+"\t"+arg0.getMonth()+"\t"+v.get();//"\t"是制表符 arg2.write(new Text(msg), NullWritable.get()); if(i==3){ break; } } } } public static void main(String[] args) { Configuration config =new Configuration(); // config.set("fs.defaultFS", "hdfs://HadoopMaster:9000"); // config.set("yarn.resourcemanager.hostname", "HadoopMaster"); // config.set("mapred.jar", "C:\\Users\\Administrator\\Desktop\\wc.jar"); // config.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator", ",");//默认分隔符是制表符"\t",这里自定义,如"," try { FileSystem fs =FileSystem.get(config); Job job =Job.getInstance(config); job.setJarByClass(RunJob.class); job.setJobName("weather"); job.setMapperClass(WeatherMapper.class); job.setReducerClass(WeatherReducer.class); job.setMapOutputKeyClass(MyKey.class); job.setMapOutputValueClass(DoubleWritable.class); job.setPartitionerClass(MyPartitioner.class); job.setSortComparatorClass(MySort.class); job.setGroupingComparatorClass(MyGroup.class); job.setNumReduceTasks(3); job.setInputFormatClass(KeyValueTextInputFormat.class); // FileInputFormat.addInputPath(job, new Path("hdfs://HadoopMaster:9000/weather.txt"));//输入路径,下有weather.txt // // Path outpath =new Path("hdfs://HadoopMaster:9000/out/weather"); FileInputFormat.addInputPath(job, new Path("./data/weather.txt"));//输入路径,下有weather.txt Path outpath =new Path("./out/weather"); if(fs.exists(outpath)){ fs.delete(outpath, true); } FileOutputFormat.setOutputPath(job, outpath); boolean f= job.waitForCompletion(true); if(f){ } } catch (Exception e) { e.printStackTrace(); } } } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6164729.html,如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码