hadoop 2 cachefile 分布式缓存 和 Configuration set get 的用法

本文详细介绍了使用Hadoop和MapReduce实现单词计数的方法,包括配置、设置、映射和归约过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.wc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WordCount {
	public static class TokenizerMapper extends
			Mapper<Object, Text, Text, IntWritable> {
		Logger logger=LoggerFactory.getLogger(TokenizerMapper.class);
		private final static IntWritable one = new IntWritable(1);
		private Text word = new Text();
		private Set<String> set;
		 private FileSystem hdfs;
		@Override
		protected void setup(org.apache.hadoop.mapreduce.Mapper.Context context)
				throws IOException, InterruptedException {
			
			super.setup(context);
			set=new HashSet<String>();
 
			Configuration conf = context.getConfiguration();
			logger.warn("welcome :"+conf.get("welcome"));
			
			URI[] patternsURIs = Job.getInstance(conf).getCacheFiles();
			
		    Path patternsPath = new Path(patternsURIs[0].getPath());
		    String patternsFileName = patternsPath.getName().toString();
		    logger.warn("patternsFileName :"+patternsFileName);
			
			BufferedReader br=new BufferedReader(new FileReader(patternsFileName));
			String line=null;
			while((line=br.readLine())!=null)
			{
				logger.warn("line :"+line);
				line=line.trim();
				set.add(line);
			}
		}
		
		  
		// value已经是文件内容的一行
		public void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			StringTokenizer itr = new StringTokenizer(value.toString());
			while (itr.hasMoreTokens()) {
				String token = itr.nextToken();
				
				if(set.contains(word.toString()))
				{
					token+="ThisIsACachedWord";
				}
				word.set(token);
				context.write(word, one);
				logger.warn("the word is :"+word);
			}
		}
	}

	public static class IntSumReducer extends
			Reducer<Text, IntWritable, Text, IntWritable> {
		private IntWritable result = new IntWritable();

		public void reduce(Text key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();
			}
			result.set(sum);
			
			Logger logger=LoggerFactory.getLogger(TokenizerMapper.class);
			logger.warn("the sum is :" + sum);
			context.write(key, result);
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		
		String[] otherArgs = new GenericOptionsParser(conf, args)
				.getRemainingArgs();
//		Job job = new Job(conf, "word count");
		conf.set("welcome", "hello HI");
		Job job = Job.getInstance(conf, WordCount.class.getName());
		job.addCacheFile(new Path(args[2]).toUri());
		job.setJarByClass(WordCount.class);
		job.setMapperClass(TokenizerMapper.class);
		job.setCombinerClass(IntSumReducer.class);
		job.setReducerClass(IntSumReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}

### 配置使用Redis与Hadoop分布式集群 在Hadoop分布式环境中集成配置Redis可以通过以下几个方面来实现: #### 1. Hadoop与Redis的功能协同 Hadoop主要用于大数据存储批处理计算,而Redis则擅长于高速缓存实时数据访问。通过将两者结合起来,可以利用Redis作为Hadoop作业的中间状态存储或者查询加速工具[^1]。 #### 2. 安装启动Redis集群 按照已有的文档说明完成Redis集群的搭建工作。确保Redis集群处于正常运行状态,并能够提供高可用性负载均衡功能[^2]。例如,在哨兵模式下部署Redis集群时,需设置主从复制以及故障转移机制。 ```bash redis-server /path/to/redis.conf --cluster-enabled yes \ --cluster-config-file nodes-6379.conf \ --appendonly yes ``` 此命令会启用Redis Cluster模式并开启持久化选项`appendonly`[^3]。 #### 3. 修改Hadoop配置文件支持Redis连接 编辑Hadoop的相关XML配置文件(如`core-site.xml`, `hdfs-site.xml`) ,增加必要的参数以便让MapReduce程序或者其他组件能识别外部服务地址。比如定义一个自定义属性指向Redis服务器列表: ```xml <property> <name>mapreduce.job.cache.files</name> <value>http://your_redis_host:port/dbfile</value> </property> ``` 上述例子展示了如何把远程资源加载进来供MR框架读取[^4]。如果需要更复杂的交互逻辑,则可能涉及到编写特定的应用层代码去操作Redis API。 #### 4. 编写应用程序调用Redis接口 开发人员可以根据实际需求设计相应的算法流程图,在其中加入针对Redis的操作步骤。对于Java开发者来说,Jedis库是一个不错的选择;Python用户可以选择redis-py包等等。下面给出一段简单的伪代码示范怎样在一个Mapper函数内部保存临时结果至Redis实例里头: ```java import redis.clients.jedis.Jedis; public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable>{ private transient Jedis jedis; @Override protected void setup(Context context)throws IOException, InterruptedException { super.setup(context); String redisHost = context.getConfiguration().get("redis.host"); int redisPort = Integer.parseInt(context.getConfiguration().get("redis.port")); this.jedis = new Jedis(redisHost, redisPort); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ //...业务逻辑省略... jedis.set(key.toString(), someValue); } } ``` 以上片段演示了如何初始化Jedis对象并与之通信。 #### 5. 测试验证整个架构的有效性 最后一步就是进行全面测试,确认所有的子系统都能够无缝协作起来达成预期目标。包括但不限于压力测验、恢复能力评估等方面的内容。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值