首页 文章 精选 留言 我的

精选列表

搜索[Linux版本],共10000篇文章
优秀的个人博客,低调大师

会员卡模板查询接口(alipay.marketing.card.template.query)JAVA版本demo

说明: 该接口主要用于查询已创建的会员卡模板参数详细信息,官方接口文档请点击【会员卡模板查询接口】 创建模板接口参考该贴:[url]https://openclub.alipay.com/read.php?tid=1577&fid=71[/url] 修改模板接口参考该贴:[url]https://openclub.alipay.com/read.php?tid=4503&fid=71[/url]代码调用示例: //alipay.marketing.card.template.query (会员卡模板查询接口) public static void template_query(){ AlipayClient alipayClient=alipa

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

会员卡模板修改接口(alipay.marketing.card.template.modify)JAVA版本demo

说明: 该接口主要用于创建之后的会员卡的模板修改,官方接口文档请点击【会员卡模板修改】 创建模板接口请参考我的这个帖子:[url]https://openclub.alipay.com/read.php?tid=1577&fid=71[/url]接口调用示例: //alipay.marketing.card.template.modify (会员卡模板修改) public static void template_modify(){ AlipayClient alipayClient=alipayclient(); AlipayMarketingCardTemplateModifyRequest request = new AlipayMarketingCardTe

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

全网第一篇SIP协议之GB28181注册(JAVA版本)

鉴于网上大部分关于SIP注册服务器编写都是C/C++/python,故开此贴,JAVA实现也贴出分享 GB28181定义了了 基于SIP架构的 视频监控互联规范,而对于多数私有协议实现的监控系统如果想接入SIP架构,就要借助网关,GB28181 规范了实现 SIP 监控域与非SIP 监控域互联。 以下是我在实际使用过程中总结的一些问题: 1. 当客户端第一次接入时,客户端将持续向Server端发送REGISTER消息,直到Server端回复"200 OK"后结束; 2. GB28181的注册流程牵扯用户认证,所以相对比较复杂,不过这也是安防通讯安全方面的一个亮点; 它的注册流程如下图: 用抓包工具看,如下图所示 注册流程: 1.客户端向服务器无限期发送Register消息: 这里客户端期初发送的Register消息为最简单的消息 2.当服务器接收到消息后,回送一个 401 消息“Unauthorized”,并在消息包头添加如下字段: 如下所示,这就是客户端接到401-Unauthorized之后再次发来的REGISTER消息,并且还附带了Auth字段,而第一次REGISTER消息是没有这个字段的: 完整的401回复如下(通过抓包工具Wireshark抓到的): Via: SIP/2.0/UDP 172.24.20.109:5060;rport=5060;received=172.24.20.109;branch=z9hG4bK352707374 From: <sip:34020000001320000002@172.24.20.109:5060>;tag=2109371333 To: <sip:34020000001320000002@172.24.20.109:5060>;tag=888 Call-ID: 545122524@172.24.20.109 CSeq: 1 REGISTER WWW-Authenticate: Digest realm="3402000000",nonce="1677f194104d46aea6c9f8aebe507017" Content-Length: 0 第二次REGISTER,也就是附带了Auth字段的报文: ìKC8¯)à¯Eóßz@@×Ǭm¬ÄÄßyÁREGISTER sip:34020000002000000001@172.24.20.26:5060 SIP/2.0 Via: SIP/2.0/UDP 172.24.20.109:5060;rport;branch=z9hG4bK742316145 Route: <sip:34020000001320000002@172.24.20.26:5060;lr> From: <sip:34020000001320000002@172.24.20.109:5060>;tag=2109371333 To: <sip:34020000001320000002@172.24.20.109:5060> Call-ID: 545122524@172.24.20.109 CSeq: 2 REGISTER Contact: <sip:34020000001320000002@172.24.20.109:5060> Authorization: Digest username="34020000001320000002", realm="3402000000", nonce="1677f194104d46aea6c9f8aebe507017", uri="sip:34020000002000000001@172.24.20.26:5060", response="dca920f418cecae456bc1566c5ac7da5", algorithm=MD5 Max-Forwards: 70 User-Agent: SIP UAS V2.1.2.438058 Expires: 3600 Content-Length: 0 验证算法如下: HA1=MD5(username:realm:passwd) #username和realm在字段“Authorization”中可以找到,passwd这个是由客户端和服务器协商得到的,一般情况下UAC端存一个UAS也知道的密码就行了 HA2=MD5(Method:Uri) #Method一般有INVITE, ACK, OPTIONS, BYE, CANCEL, REGISTER;Uri可以在字段“Authorization”找到 response = MD5(HA1:nonce:HA2) 算法来源:http://tools.ietf.org/html/rfc2069[Page 6] 关键认证算法的JAVA实现(注意冒号是必须要的): public static void main(String[] args) throws Exception { String ha1 = md5("34020000001320000002" + ":" + "3402000000" + ":" + "admin123", ""); //HA1=MD5(username:realm:passwd) String ha2 = md5("REGISTER" + ":" + "sip:34020000002000000001@172.24.20.26:5060", ""); //HA2=MD5(Method:Uri) String response = ha1 + ":" + "326d59f91b6e448fa461fcacd9161abe" + ":" + ha2; System.out.println("MD5加密后的字符串为:encodeStr="+md5(response, "")); } MD5工具类 import org.apache.commons.codec.digest.DigestUtils; public class MD5Utils { /** * MD5方法 * * @param text 明文 * @param key 密钥 * @return 密文 * @throws Exception */ public static String md5(String text, String key) { //加密后的字符串 String encodeStr=DigestUtils.md5Hex(text + key); return encodeStr; } /** * MD5验证方法 * * @param text 明文 * @param key 密钥 * @param md5 密文 * @return true/false * @throws Exception */ public static boolean verify(String text, String key, String md5) throws Exception { //根据传入的密钥进行验证 String md5Text = md5(text, key); if(md5Text.equalsIgnoreCase(md5)) { System.out.println("MD5验证通过"); return true; } return false; } } 最后运行流程如下: 注册服务器核心代码: import java.text.ParseException; import java.util.TooManyListenersException; import javax.sip.InvalidArgumentException; import javax.sip.ObjectInUseException; import javax.sip.PeerUnavailableException; import javax.sip.SipException; import javax.sip.TransportNotSupportedException; import org.apache.commons.lang.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SIPMain { protected Logger logger = LoggerFactory.getLogger(SIPMain.class); public void run() { //用户名,IP地址,端口 try { int port = 5060; SipLayer sipLayer = new SipLayer("admin" , "172.24.20.26" , port); //本地 //SipLayer sipLayer = new SipLayer("admin","xx.xx.xx.xx",port); //阿里云上的IP VECS01532 sipLayer.setMessageProcessor(new MessageProcessorImpl()); System.out.println("服务启动完毕, 已经在"+port+"端口监听消息\n\n"); } catch (PeerUnavailableException e) { e.printStackTrace(); logger.error(ExceptionUtils.getFullStackTrace(e)); } catch (TransportNotSupportedException e) { e.printStackTrace(); logger.error(ExceptionUtils.getFullStackTrace(e)); } catch (ObjectInUseException e) { e.printStackTrace(); logger.error(ExceptionUtils.getFullStackTrace(e)); } catch (InvalidArgumentException e) { e.printStackTrace(); logger.error(ExceptionUtils.getFullStackTrace(e)); } catch (TooManyListenersException e) { e.printStackTrace(); logger.error(ExceptionUtils.getFullStackTrace(e)); } } /** * 这个方法暂时用不上,目前系统没有需要主动发送消息给SIP终端设备的业务场景 * @throws InvalidArgumentException * @throws TooManyListenersException * @throws ParseException * @throws SipException */ public void sendMsg() throws InvalidArgumentException, TooManyListenersException, ParseException, SipException{ SipLayer sipLayer = new SipLayer("admin","127.0.0.1",5060); sipLayer.sendMessage(sipLayer.getUsername(), sipLayer.getHost(), "test message"); } } SipLayer.java代码: import java.text.ParseException; import java.util.ArrayList; import java.util.Properties; import java.util.TooManyListenersException; import javax.sip.DialogTerminatedEvent; import javax.sip.IOExceptionEvent; import javax.sip.InvalidArgumentException; import javax.sip.ListeningPoint; import javax.sip.ObjectInUseException; import javax.sip.PeerUnavailableException; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.SipException; import javax.sip.SipFactory; import javax.sip.SipListener; import javax.sip.SipProvider; import javax.sip.SipStack; import javax.sip.TimeoutEvent; import javax.sip.TransactionTerminatedEvent; import javax.sip.TransportNotSupportedException; import javax.sip.address.Address; import javax.sip.address.AddressFactory; import javax.sip.address.SipURI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.FromHeader; import javax.sip.header.HeaderFactory; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.MessageFactory; import javax.sip.message.Request; import javax.sip.message.Response; public class SipLayer implements SipListener { private MessageProcessor messageProcessor; private String username; private SipStack sipStack; private SipFactory sipFactory; private AddressFactory addressFactory; private HeaderFactory headerFactory; private MessageFactory messageFactory; private SipProvider sipProvider; /** Here we initialize the SIP stack. */ @SuppressWarnings("deprecation") public SipLayer(String username, String ip, int port) throws PeerUnavailableException, TransportNotSupportedException, InvalidArgumentException, ObjectInUseException, TooManyListenersException { setUsername(username); sipFactory = SipFactory.getInstance(); sipFactory.setPathName("gov.nist"); Properties properties = new Properties(); properties.setProperty("javax.sip.STACK_NAME", "cameraReg"); properties.setProperty("javax.sip.IP_ADDRESS", ip); /** * sip_server_log.log 和 sip_debug_log.log * public static final int TRACE_NONE = 0; public static final int TRACE_MESSAGES = 16; public static final int TRACE_EXCEPTION = 17; public static final int TRACE_DEBUG = 32; */ properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "16"); properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "sip_server_log"); properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "sip_debug_log"); sipStack = sipFactory.createSipStack(properties); headerFactory = sipFactory.createHeaderFactory(); addressFactory = sipFactory.createAddressFactory(); messageFactory = sipFactory.createMessageFactory(); ListeningPoint tcp = sipStack.createListeningPoint(port, "tcp"); ListeningPoint udp = sipStack.createListeningPoint(port, "udp"); sipProvider = sipStack.createSipProvider(tcp); sipProvider.addSipListener(this); sipProvider = sipStack.createSipProvider(udp); sipProvider.addSipListener(this); } /** * This method uses the SIP stack to send a message. 第一个参数:用户名 第二个参数:IP地址 * 第三个参数:消息内容 */ public void sendMessage(String username, String address, String message) throws ParseException, InvalidArgumentException, SipException { SipURI from = addressFactory.createSipURI(getUsername(), getHost() + ":" + getPort()); Address fromNameAddress = addressFactory.createAddress(from); fromNameAddress.setDisplayName(getUsername()); FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "cameraReg1.0"); SipURI toAddress = addressFactory.createSipURI(username, address); Address toNameAddress = addressFactory.createAddress(toAddress); toNameAddress.setDisplayName(username); ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null); SipURI requestURI = addressFactory.createSipURI(username, address); requestURI.setTransportParam("udp"); ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(); ViaHeader viaHeader = headerFactory.createViaHeader(getHost(), getPort(), "udp", "branch1"); viaHeaders.add(viaHeader); CallIdHeader callIdHeader = sipProvider.getNewCallId(); @SuppressWarnings("deprecation") CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1, Request.MESSAGE); MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70); Request request = messageFactory.createRequest(requestURI, Request.MESSAGE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards); SipURI contactURI = addressFactory.createSipURI(getUsername(), getHost()); contactURI.setPort(getPort()); Address contactAddress = addressFactory.createAddress(contactURI); contactAddress.setDisplayName(getUsername()); ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress); request.addHeader(contactHeader); ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain"); request.setContent(message, contentTypeHeader); sipProvider.sendRequest(request); } /** This method is called by the SIP stack when a response arrives. */ public void processResponse(ResponseEvent evt) { Response response = evt.getResponse(); int status = response.getStatusCode(); if ((status >= 200) && (status < 300)) { // Success! messageProcessor.processInfo("--Sent"); return; } messageProcessor.processError("Previous message not sent: " + status); } /** * SIP服务端接收消息的方法 * Content 里面是GBK编码 * This method is called by the SIP stack when a new request arrives. */ public void processRequest(RequestEvent evt) { Request req = evt.getRequest(); messageProcessor.processMessage(req,messageFactory,sipProvider); } /** * This method is called by the SIP stack when there's no answer to a * message. Note that this is treated differently from an error message. */ public void processTimeout(TimeoutEvent evt) { messageProcessor.processError("Previous message not sent: " + "timeout"); } /** * This method is called by the SIP stack when there's an asynchronous * message transmission error. */ public void processIOException(IOExceptionEvent evt) { messageProcessor.processError("Previous message not sent: " + "I/O Exception"); } /** * This method is called by the SIP stack when a dialog (session) ends. */ public void processDialogTerminated(DialogTerminatedEvent evt) { } /** * This method is called by the SIP stack when a transaction ends. */ public void processTransactionTerminated(TransactionTerminatedEvent evt) { } @SuppressWarnings("deprecation") public String getHost() { String host = sipStack.getIPAddress(); return host; } @SuppressWarnings("deprecation") public int getPort() { int port = sipProvider.getListeningPoint().getPort(); return port; } public String getUsername() { return username; } public void setUsername(String newUsername) { username = newUsername; } public MessageProcessor getMessageProcessor() { return messageProcessor; } public void setMessageProcessor(MessageProcessor newMessageProcessor) { messageProcessor = newMessageProcessor; } } MessageProcessor接口: import javax.sip.SipProvider; import javax.sip.message.MessageFactory; import javax.sip.message.Request; /** * 消息处理回调函数接口 */ public interface MessageProcessor { /** * 接收IPCamera发来的SIP协议消息的时候产生的回调函数 */ public void processMessage(Request req,MessageFactory messageFactory, SipProvider sipProvider); public void processError(String errorMessage); public void processInfo(String infoMessage); } MessageProcessor实现类这里不给出,因为里面包含了很多本公司SIP注册业务的具体细节 需要提示的一点是,需要安装一个反编译工具去阅读Request源码里面的属性和方法 ,以获取SIP报文里面的内容 比如获取我想获取sender和method字段 FromHeader fromHeader = (FromHeader) req.getHeader("From"); String sender = fromHeader.getAddress().toString(); String method = req.getMethod(); 再比如我想获取Contact字段 Contact contact = (Contact) req.getHeader("Contact"); 类似于这样,关键是去通过eclipse点进去看一下这个Request的源码 最后,给出JAVA SIP协议的支持包MAVEN POM依赖: <!-- SPI协议相关的包 --> <dependency> <groupId>javax.sip</groupId> <artifactId>jain-sip-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.sip</groupId> <artifactId>jain-sip-ri</artifactId> <version>1.2</version> </dependency>

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

业余草 SpringCloud教程 | 第八篇: 消息总线(Spring Cloud Bus)(Finchley版本)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xmt1139057136/article/details/81412869 Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。本文要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。 一、准备工作 本文还是基于上一篇文章来实现。按照官方文档,我们只需要在配置文件中配置 spring-cloud-starter-bus-amqp ;这就是说我们需要装rabbitMq,点击rabbitmq下载。至于怎么使用 rabbitmq,搜索引擎下。 二、改造config-client 在pom文件加上起步依赖spring-cloud-starter-bus-amqp,完整的配置文件如下: <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> 在配置文件application.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码。并需要加上spring.cloud.bus的三个配置,具体如下: spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.cloud.bus.enabled=true spring.cloud.bus.trace.enabled=true management.endpoints.web.exposure.include=bus-refresh ConfigClientApplication启动类代码如下: @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @RestController @RefreshScope public class ConfigClientApplication { /** * http://localhost:8881/actuator/bus-refresh */ public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); } @Value("${foo}") String foo; @RequestMapping(value = "/hi") public String hi(){ return foo; } } 依次启动eureka-server、confg-cserver,启动两个config-client,端口为:8881、8882。 访问http://localhost:8881/hi或者http://localhost:8882/hi浏览器显示: foo version 3 这时我们去代码仓库将foo的值改为“foo version 4”,即改变配置文件foo的值。如果是传统的做法,需要重启服务,才能达到配置文件的更新。此时,我们只需要发送post请求:http://localhost:8881/actuator/bus-refresh,你会发现config-client会重新读取配置文件 重新读取配置文件: 这时我们再访问http://localhost:8881/hi或者http://localhost:8882/hi浏览器显示: foo version 4 另外,/actuator/bus-refresh接口可以指定服务,即使用”destination”参数,比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服务名为customers的所有服务。 三、分析 此时的架构图: 当git文件更改的时候,通过pc端用post 向端口为8882的config-client发送请求/bus/refresh/;此时8882端口会发送一个消息,由消息总线向其他服务传递,从而使整个微服务集群都达到更新配置文件。 本文源码下载: https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter8 五、参考资料 http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html 感谢您的关注!可加QQ1群:135430763,QQ2群:454796847,QQ3群:187424846。QQ群进群密码:xttblog,想加微信群的朋友,可以微信搜索:xmtxtt,备注:“xttblog”,添加助理微信拉你进群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作可添加助理微信进行沟通!

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

Hadoop MapReduce编程 API入门系列之统计学生成绩版本2(十八)

统计出每个年龄段的 男、女 学生的最高分 这里,为了空格符的差错,直接,我们有时候,像如下这样的来排数据。 代码 package zhouls.bigdata.myMapReduce.Gender; import java.io.IOException; 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.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Reducer; 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 统计不同年龄段内 男、女最高分数 * * */ /* Alice<tab>23<tab>female<tab>45 Bob<tab>34<tab>male<tab>89 Chris<tab>67<tab>male<tab>97 Kristine<tab>38<tab>female<tab>53 Connor<tab>25<tab>male<tab>27 Daniel<tab>78<tab>male<tab>95 James<tab>34<tab>male<tab>79 Alex<tab>52<tab>male<tab>69 Nancy<tab>7<tab>female<tab>98 Adam<tab>9<tab>male<tab>37 Jacob<tab>7<tab>male<tab>23 Mary<tab>6<tab>female<tab>93 Clara<tab>87<tab>female<tab>72 Monica<tab>56<tab>female<tab>92 */ public class Gender extends Configured implements Tool { /* * * @function Mapper 解析输入数据,然后按需求输出 * @input key=行偏移量 value=学生数据 * @output key=gender value=name+age+score * */ public static class PCMapper extends Mapper<Object, Text, Text, Text> { public void map(Object key, Text value, Context context) throws IOException, InterruptedException {//拿Alice<tab>23<tab>female<tab>45 String[] tokens = value.toString().split("<tab>");//使用分隔符<tab>,将数据解析为数组 tokens //得到Alice 23 female 45 //即tokens[0] tokens[1] tokens[2] tokens[3] String gender = tokens[2].toString();//性别 String nameAgeScore = tokens[0] + "\t" + tokens[1] + "\t"+ tokens[3]; //输出 key=gender value=name+age+score //输出 key=female value=Alice +23+45 context.write(new Text(gender), new Text(nameAgeScore));//将 (female , Alice+ 23+ 45) 写入到context中 } } public static class MyHashPartitioner extends Partitioner<Text, Text> { /** Use {@link Object#hashCode()} to partition. */ @Override public int getPartition(Text key, Text value,int numReduceTasks) { return (key.hashCode()) % numReduceTasks; } } /** * * @function Partitioner 根据 age 选择 reduce 分区 * */ public static class PCPartitioner extends Partitioner<Text, Text> { @Override public int getPartition(Text key, Text value, int numReduceTasks) { // TODO Auto-generated method stub String[] nameAgeScore = value.toString().split("\t"); String age = nameAgeScore[1];//学生年龄 int ageInt = Integer.parseInt(age);//按年龄段分区 // 默认指定分区 0 if (numReduceTasks == 0) return 0; //年龄小于等于20,指定分区0 if (ageInt <= 20) { return 0; } // 年龄大于20,小于等于50,指定分区1 if (ageInt > 20 && ageInt <= 50) { return 1 % numReduceTasks; } // 剩余年龄,指定分区2 else return 2 % numReduceTasks; } } /** * * @function 定义Combiner 合并 Mapper 输出结果 * */ public static class PCCombiner extends Reducer<Text, Text, Text, Text> { private Text text = new Text(); public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException { int maxScore = Integer.MIN_VALUE; String name = " "; String age = " "; int score = 0; for (Text val : values) { String[] valTokens = val.toString().split("\\t"); score = Integer.parseInt(valTokens[2]); if (score > maxScore) { name = valTokens[0]; age = valTokens[1]; maxScore = score; } } text.set(name + "\t" + age + "\t" + maxScore); context.write(key, text); } } /* * * @function Reducer 统计出 不同年龄段、不同性别 的最高分 * input key=gender value=name+age+score * output key=name value=age+gender+score * */ static class PCReducer extends Reducer<Text, Text, Text, Text> { @Override public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException { int maxScore = Integer.MIN_VALUE; String name = " "; String age = " "; String gender = " "; int score = 0; // 根据key,迭代 values 集合,求出最高分 for (Text val : values) { String[] valTokens = val.toString().split("\\t"); score = Integer.parseInt(valTokens[2]); if (score > maxScore) { name = valTokens[0]; age = valTokens[1]; gender = key.toString(); maxScore = score; } } context.write(new Text(name), new Text("age- " + age + "\t" + gender + "\tscore-" + maxScore)); } } /** * @function 任务驱动方法 * @param args * @return * @throws Exception */ @Override public int run(String[] args) throws Exception { // TODO Auto-generated method stub Configuration conf = new Configuration();//读取配置文件 Path mypath = new Path(args[1]); FileSystem hdfs = mypath.getFileSystem(conf); if (hdfs.isDirectory(mypath)) { hdfs.delete(mypath, true); } @SuppressWarnings("deprecation") Job job = new Job(conf, "gender");//新建一个任务 job.setJarByClass(Gender.class);//主类 job.setMapperClass(PCMapper.class);//Mapper job.setReducerClass(PCReducer.class);//Reducer job.setPartitionerClass(MyHashPartitioner.class); //job.setPartitionerClass(PCPartitioner.class);//设置Partitioner类 job.setNumReduceTasks(3);// reduce个数设置为3 job.setMapOutputKeyClass(Text.class);//map 输出key类型 job.setMapOutputValueClass(Text.class);//map 输出value类型 job.setCombinerClass(PCCombiner.class);//设置Combiner类 job.setOutputKeyClass(Text.class);//输出结果 key类型 job.setOutputValueClass(Text.class);//输出结果 value 类型 FileInputFormat.addInputPath(job, new Path(args[0]));// 输入路径 FileOutputFormat.setOutputPath(job, new Path(args[1]));// 输出路径 job.waitForCompletion(true);//提交任务 return 0; } /** * @function main 方法 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // String[] args0 = { // "hdfs://HadoopMaster:9000/gender/gender.txt", // "hdfs://HadoopMaster:9000/out/partition/" }; String[] args0 = { "./data/gender/gender.txt", "./out/gender" }; int ec = ToolRunner.run(new Configuration(),new Gender(), args0); System.exit(ec); } } 或者 代码 package com.dajiangtai.hadoop.junior; import java.io.IOException; 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.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Reducer; 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 zhouls * */ /* Alice<tab>23<tab>female<tab>45 Bob<tab>34<tab>male<tab>89 Chris<tab>67<tab>male<tab>97 Kristine<tab>38<tab>female<tab>53 Connor<tab>25<tab>male<tab>27 Daniel<tab>78<tab>male<tab>95 James<tab>34<tab>male<tab>79 Alex<tab>52<tab>male<tab>69 Nancy<tab>7<tab>female<tab>98 Adam<tab>9<tab>male<tab>37 Jacob<tab>7<tab>male<tab>23 Mary<tab>6<tab>female<tab>93 Clara<tab>87<tab>female<tab>72 Monica<tab>56<tab>female<tab>92 */ public class Gender extends Configured implements Tool { /* * * @function Mapper 解析输入数据,然后按需求输出 * @input key=行偏移量 value=学生数据 * @output key=gender value=name+age+score * */ public static class PCMapper extends Mapper<Object, Text, Text, Text> { public void map(Object key, Text value, Context context) throws IOException, InterruptedException {//拿Alice<tab>23<tab>female<tab>45 String[] tokens = value.toString().split("<tab>");//使用分隔符<tab>,将数据解析为数组 tokens //得到Alice 23 female 45 //即tokens[0] tokens[1] tokens[2] tokens[3] String gender = tokens[2].toString();//性别 String nameAgeScore = tokens[0] + "\t" + tokens[1] + "\t"+ tokens[3]; //输出 key=gender value=name+age+score //输出 key=female value=Alice +23+45 context.write(new Text(gender), new Text(nameAgeScore));//将 (female , Alice+ 23+ 45) 写入到context中 } } public static class MyHashPartitioner extends Partitioner<Text, Text> { /** Use {@link Object#hashCode()} to partition. */ @Override public int getPartition(Text key, Text value,int numReduceTasks) { return (key.hashCode()) % numReduceTasks; } } /** * * @function Partitioner 根据 age 选择 reduce 分区 * */ public static class PCPartitioner extends Partitioner<Text, Text> { @Override public int getPartition(Text key, Text value, int numReduceTasks) { // TODO Auto-generated method stub String[] nameAgeScore = value.toString().split("\t"); String age = nameAgeScore[1];//学生年龄 int ageInt = Integer.parseInt(age);//按年龄段分区 // 默认指定分区 0 if (numReduceTasks == 0) return 0; //年龄小于等于20,指定分区0 if (ageInt <= 20) { return 0; } // 年龄大于20,小于等于50,指定分区1 if (ageInt > 20 && ageInt <= 50) { return 1 % numReduceTasks; } // 剩余年龄,指定分区2 else return 2 % numReduceTasks; } } /** * * @function 定义Combiner 合并 Mapper 输出结果 * */ public static class PCCombiner extends Reducer<Text, Text, Text, Text> { private Text text = new Text(); public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException { int maxScore = Integer.MIN_VALUE; String name = " "; String age = " "; int score = 0; for (Text val : values) { String[] valTokens = val.toString().split("\\t"); score = Integer.parseInt(valTokens[2]); if (score > maxScore) { name = valTokens[0]; age = valTokens[1]; maxScore = score; } } text.set(name + "\t" + age + "\t" + maxScore); context.write(key, text); } } /* * * @function Reducer 统计出 不同年龄段、不同性别 的最高分 * input key=gender value=name+age+score * output key=name value=age+gender+score * */ static class PCReducer extends Reducer<Text, Text, Text, Text> { @Override public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException { int maxScore = Integer.MIN_VALUE; String name = " "; String age = " "; String gender = " "; int score = 0; // 根据key,迭代 values 集合,求出最高分 for (Text val : values) { String[] valTokens = val.toString().split("\\t"); score = Integer.parseInt(valTokens[2]); if (score > maxScore) { name = valTokens[0]; age = valTokens[1]; gender = key.toString(); maxScore = score; } } context.write(new Text(name), new Text("age- " + age + "\t" + gender + "\tscore-" + maxScore)); } } /** * @function 任务驱动方法 * @param args * @return * @throws Exception */ @Override public int run(String[] args) throws Exception { // TODO Auto-generated method stub Configuration conf = new Configuration();//读取配置文件 Path mypath = new Path(args[1]); FileSystem hdfs = mypath.getFileSystem(conf); if (hdfs.isDirectory(mypath)) { hdfs.delete(mypath, true); } @SuppressWarnings("deprecation") Job job = new Job(conf, "gender");//新建一个任务 job.setJarByClass(Gender.class);//主类 job.setMapperClass(PCMapper.class);//Mapper job.setReducerClass(PCReducer.class);//Reducer job.setPartitionerClass(MyHashPartitioner.class); //job.setPartitionerClass(PCPartitioner.class);//设置Partitioner类 job.setNumReduceTasks(3);// reduce个数设置为3 job.setMapOutputKeyClass(Text.class);//map 输出key类型 job.setMapOutputValueClass(Text.class);//map 输出value类型 job.setCombinerClass(PCCombiner.class);//设置Combiner类 job.setOutputKeyClass(Text.class);//输出结果 key类型 job.setOutputValueClass(Text.class);//输出结果 value 类型 FileInputFormat.addInputPath(job, new Path(args[0]));// 输入路径 FileOutputFormat.setOutputPath(job, new Path(args[1]));// 输出路径 job.waitForCompletion(true);//提交任务 return 0; } /** * @function main 方法 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String[] args0 = { "hdfs://master:9000/middle/partition/gender.txt", "hdfs://master:9000/middle/partition/out/" }; int ec = ToolRunner.run(new Configuration(),new Gender(), args0); System.exit(ec); } } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6165704.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文件系统,支持十年生命周期更新。

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