spark学习记录(十四、kafka)

一、简介

kafka是一个高吞吐的分布式消息队列系统。特点是生产者消费者模式,先进先出(FIFO)保证顺序,自己不丢数据,默认每隔7天清理数据。消息列队常见场景:系统之间解耦合、峰值压力缓冲、异步通信。

Kafka架构是由producer(消息生产者)、consumer(消息消费者)、borker(kafka集群的server,负责处理消息读、写请求,存储消息,在kafka cluster这一层这里,其实里面是有很多个broker)、topic(消息队列/分类相当于队列,里面有生产者和消费者模型)、zookeeper(元数据信息存在zookeeper中,包括:存储消费偏移量,topic话题信息,partition信息) 这些部分组成。

kafka里面的消息是有topic来组织的,简单的我们可以想象为一个队列,一个队列就是一个topic,然后它把每个topic又分为很多个partition,这个是为了做并行的,在每个partition内部消息强有序,相当于有序的队列,其中每个消息都有个序号offset,比如0到12,从前面读往后面写。一个partition对应一个broker,一个broker可以管多个partition,比如说,topic有6个partition,有两个broker,那每个broker就管3个partition。这个partition可以很简单想象为一个文件,当数据发过来的时候它就往这个partition上面append,追加就行,消息不经过内存缓冲,直接写入文件,kafka和很多消息系统不一样,很多消息系统是消费完了我就把它删掉,而kafka是根据时间策略删除,而不是消费完就删除,在kafka里面没有一个消费完这么个概念,只有过期这样一个概念。

producer自己决定往哪个partition里面去写,这里有一些的策略,譬如如果hash,不用多个partition之间去join数据了。consumer自己维护消费到哪个offset,每个consumer都有对应的group,group内是queue消费模型(各个consumer消费不同的partition,因此一个消息在group内只消费一次),group间是publish-subscribe消费模型,各个group各自独立消费,互不影响,因此一个消息在被每个group消费一次。

kafka的特点:

  • 系统的特点:生产者消费者模型,FIFO

Partition内部是FIFO的,partition之间不是FIFO的,当然我们可以把topic设为一个partition,这样就是严格的FIFO。

  • 高性能:单节点支持上千个客户端,百MB/s吞吐,接近网卡的极限
  • 持久性:消息直接持久化在普通磁盘上且性能好

直接写到磁盘中去,就是直接append到磁盘里去,这样的好处是直接持久化,数据不会丢失,第二个好处是顺序写,然后消费数据也是顺序的读,所以持久化的同时还能保证顺序,比较好,因为磁盘顺序读比较好。

  • 分布式:数据副本冗余、流量负载均衡、可扩展

分布式,数据副本,也就是同一份数据可以到不同的broker上面去,也就是当一份数据,磁盘坏掉的时候,数据不会丢失,比如3个副本,就是在3个机器磁盘都坏掉的情况下数据才会丢,在大量使用情况下看这样是非常好的,负载均衡,可扩展,在线扩展,不需要停服务。

  • 很灵活:消息长时间持久化+Client维护消费状态

消费方式非常灵活,第一原因是消息持久化时间跨度比较长,一天或者一星期等,第二消费状态自己维护消费到哪个地方了可以自定义消费偏移量。

kafka名词解释:

kafka的leader的均衡机制 :

当一个broker停止或者crashes时,所有本来将它作为leader的分区将会把leader转移到其他broker上去,极端情况下,会导致同一个leader管理多个分区,导致负载不均衡,同时当这个broker重启时,如果这个broker不再是任何分区的leader,kafka的client也不会从这个broker来读取消息,从而导致资源的浪费。

kafka中有一个被称为优先副本(preferred replicas)的概念。如果一个分区有3个副本,且这3个副本的优先级别分别为0,1,2,根据优先副本的概念,0会作为leader 。当0节点的broker挂掉时,会启动1这个节点broker当做leader。当0节点的broker再次启动后,会自动恢复为此partition的leader。不会导致负载不均衡和资源浪费,这就是leader的均衡机制。

二、集群搭建

  • kafka:分布式消息系统,将消息直接存入磁盘,默认保存一周。
  • broker:组成kafka集群的节点,之间没有主从关系。依赖zookeeper来协调,broker负责消息的读写与存储,一个broker可以管理多个partition。
  • producer:消息的生产者,自己决定向那个partition中去生产消息,两种机制:hash,轮询。
  • consumer:消息的消费者,consumer通过zookeeper去维护消费者偏移量。consumer有自己的消费者组,不同组之间消费同一个topic数据,互不影响,相同的组内的不同consumer消费者消费同一个topic,这个topic中相同的数据只能被消费一次。
  • topic:一类消息总称/一个消息队列。topic是由partition组成,创建指定个数。
  • partition:组成topic的单元,每个partition有副本,创建topic时指定副本个数,每个partition只能由一个broker管理,这个broker是这个partition的leader。
  • zookeeper:协调kafka broker,存储原数据:consumer的offset+broker信息+topic信息+partition信息

1.上传并解压kafka-2.1.0-src.tgz

2.修改config下的server.properties

zookeeper.connect=hadoop1:2181,hadoop2:2181,hadoop3:2181
port=9092

3.将文件复制到其他主机上

scp -r kafka_2.11-2.1.0/ hadoop3:/usr/local/

4.修改config下的server.properties

三台机器broker.id分别为0,1,2

5.启动zookeeper集群

6.启动kafka

在bin目录下启动

./kafka-server-start.sh -daemon ../config/server.properties

7.检验

三、相关命令 

创建topic:

./kafka-topics.sh --zookeeper node3:2181,node4:2181,node5:2181  --create --topic topic2017 --partitions 3 --replication-factor 3

用一台节点控制台来当kafka的生产者:

./kafka-console-producer.sh  --topic  topic2017
--broker-list node1:9092,node2:9092,node3:9092

用另一台节点控制台来当kafka的消费者:

查看kafka中topic列表:

./kafka-topics.sh  --list --zookeeper node3:2181,node4:2181,node5:2181

查看kafka中topic的描述:

./kafka-topics.sh --describe --zookeeper node3:2181,node4:2181,node5:2181  --topic topic2017

 

查看zookeeper中topic相关信息:

​启动zookeeper客户端:
./zkCli.sh
查看topic相关信息:
ls /brokers/topics/
查看消费者相关信息:
ls /consumers

删除kafka中的数据:

  • ​​​​在kafka集群中删除topic,当前topic被标记成删除。
./kafka-topics.sh --zookeeper node3:2181,node4:2181,node5:2181 --delete --topic t1205
  • 进入zookeeper客户端,删除topic信息在每台broker节点上删除当前这个topic对应的真实数据。
rmr /brokers/topics/t1205
  • 删除zookeeper中被标记为删除的topic信息
rmr /admin/delete_topics/t1205

四、SparkStreaming+kafka 

在SparkStreaming程序运行起来后,Executor中会有receiver tasks接收kafka推送过来的数据。数据会被持久化,默认级别为MEMORY_AND_DISK_SER_2,这个级别也可以修改。receiver task对接收过来的数据进行存储和备份,这个过程会有节点之间的数据传输。备份完成后去zookeeper中更新消费偏移量,然后向Driver中的receiver tracker汇报数据的位置。最后Driver根据数据本地化将task分发到不同节点上执行。

当Driver进程挂掉后,Driver下的Executor都会被杀掉,当更新完zookeeper消费偏移量的时候,Driver如果挂掉了,就会存在找不到数据的问题,相当于丢失数据。

如何解决这个问题?

开启WAL(write ahead log)预写日志机制,在接受过来数据备份到其他节点的时候,同时备份到HDFS上一份(我们需要将接收来的数据的持久化级别降级到MEMORY_AND_DISK),这样就能保证数据的安全性。不过,因为写HDFS比较消耗性能,要在备份完数据之后才能进行更新zookeeper以及汇报位置等,这样会增加job的执行时间,这样对于任务的执行提高了延迟度。

receiver的并行度设置:

receiver的并行度是由spark.streaming.blockInterval来决定的,默认为200ms,假设batchInterval为5s,那么每隔blockInterval就会产生一个block,这里就对应每批次产生RDD的partition,这样5秒产生的这个Dstream中的这个RDD的partition为25个,并行度就是25。如果想提高并行度可以减少blockInterval的数值,但是最好不要低于50ms。

public class JavaExample {
    public static void main(String[] args) throws InterruptedException {
        SparkConf conf = new SparkConf();
        conf.setMaster("local");
        conf.setAppName("SparkStreamingOnKafkaDirected");

        JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
        /**
         * 可以不设置checkpoint,不设置不保存offset,offset默认在内存中有一份,如果设置checkpoint,则在checkpoint也有一份
         */
        jsc.checkpoint("./checkpoint");
        Map<String, String> kafkaParameters = new HashMap<>();
        kafkaParameters.put("metadata.broker.list", "192.168.30.141:9092,192.168.30.139:9092,192.168.30.140:9092");

        HashSet<String> topics = new HashSet<>();
        topics.add("t0404");
        JavaPairInputDStream<String, String> lines = KafkaUtils.createDirectStream(jsc,
                String.class, String.class, StringDecoder.class, StringDecoder.class, kafkaParameters, topics);
        final JavaDStream<String> words = lines.flatMap(new FlatMapFunction<Tuple2<String, String>, String>() {
            @Override
            public Iterator<String> call(Tuple2<String, String> tuple2) throws Exception {
                return Arrays.asList(tuple2._2.split("\t")).iterator();
            }
        });

        JavaPairDStream<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }
        });

        JavaPairDStream<String, Integer> wordsCount = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });

        wordsCount.print();
        jsc.start();
        jsc.awaitTermination();
        jsc.close();
    }
}

 五、使用zookeeper管理offset

public class UseZookeeperManageOffset {
    /**
     * 使用log4j打印日志,“UseZookeeper.class” 设置日志的产生类
     */
    static final Logger logger = Logger.getLogger(UseZookeeperManageOffset.class);

    public static void main(String[] args) throws InterruptedException {
        /**
         * 加载log4j的配置文件,方便打印日志
         */
        ProjectUtil.LoadLogConfig();
        logger.info("project is starting...");
        /**
         * 从kafka集群中得到topic每个分区中生产消息的最大偏移量位置
         */
        Map<TopicAndPartition, Long> topicOffsets = GetTopicOffsetFromKafkaBroker.getTopicOffsets("node1:9092,node2:9092,node3:9092", "mytopic");

        /**
         * 从zookeeper中获取当前topic每个分区 consumer 消费的offset位置
         */
        Map<TopicAndPartition, Long> consumerOffsets =
                GetTopicOffsetFromZookeeper.getConsumerOffsets("node3:2181,node4:2181,node5:2181","zhy","mytopic");

        /**
         * 合并以上得到的两个offset ,
         * 	思路是:
         * 		如果zookeeper中读取到consumer的消费者偏移量,那么就zookeeper中当前的offset为准。
         * 		否则,如果在zookeeper中读取不到当前消费者组消费当前topic的offset,就是当前消费者组第一次消费当前的topic,
         * 			offset设置为topic中消息的最大位置。
         */
        if(null!=consumerOffsets && consumerOffsets.size()>0){
            topicOffsets.putAll(consumerOffsets);
        }
        /**
         * 如果将下面的代码解开,是将topicOffset 中当前topic对应的每个partition中消费的消息设置为0,就是从头开始。
         */
//		for(Map.Entry<TopicAndPartition, Long> item:topicOffsets.entrySet()){
//          item.setValue(0l);
//		}

        /**
         * 构建SparkStreaming程序,从当前的offset消费消息
         */
        JavaStreamingContext jsc = SparkStreamingDirect.getStreamingContext(topicOffsets,"zhy");
        jsc.start();
        jsc.awaitTermination();
        jsc.close();

    }
}
public class GetTopicOffsetFromKafkaBroker {
	public static void main(String[] args) {
		
		Map<TopicAndPartition, Long> topicOffsets = getTopicOffsets("node1:9092,node2:9092,node3:9092", "mytopic");
		Set<Entry<TopicAndPartition, Long>> entrySet = topicOffsets.entrySet();
		for(Entry<TopicAndPartition, Long> entry : entrySet) {
			TopicAndPartition topicAndPartition = entry.getKey();
			Long offset = entry.getValue();
			String topic = topicAndPartition.topic();
			int partition = topicAndPartition.partition();
			System.out.println("topic = "+topic+",partition = "+partition+",offset = "+offset);
		}
	
	}
	
	/**
	 * 从kafka集群中得到当前topic,生产者在每个分区中生产消息的偏移量位置
	 * @param KafkaBrokerServer
	 * @param topic
	 * @return
	 */
	public static Map<TopicAndPartition,Long> getTopicOffsets(String KafkaBrokerServer, String topic){
		Map<TopicAndPartition,Long> retVals = new HashMap<TopicAndPartition,Long>();
		
		for(String broker:KafkaBrokerServer.split(",")){
			
			SimpleConsumer simpleConsumer = new SimpleConsumer(broker.split(":")[0],Integer.valueOf(broker.split(":")[1]), 64*10000,1024,"consumer"); 
			TopicMetadataRequest topicMetadataRequest = new TopicMetadataRequest(Arrays.asList(topic));
			TopicMetadataResponse topicMetadataResponse = simpleConsumer.send(topicMetadataRequest);
			
			for (TopicMetadata metadata : topicMetadataResponse.topicsMetadata()) {
				for (PartitionMetadata part : metadata.partitionsMetadata()) {
					Broker leader = part.leader();
					if (leader != null) { 
						TopicAndPartition topicAndPartition = new TopicAndPartition(topic, part.partitionId()); 
						
						PartitionOffsetRequestInfo partitionOffsetRequestInfo = new PartitionOffsetRequestInfo(kafka.api.OffsetRequest.LatestTime(), 10000); 
						OffsetRequest offsetRequest = new OffsetRequest(ImmutableMap.of(topicAndPartition, partitionOffsetRequestInfo), kafka.api.OffsetRequest.CurrentVersion(), simpleConsumer.clientId()); 
						OffsetResponse offsetResponse = simpleConsumer.getOffsetsBefore(offsetRequest); 
						
						if (!offsetResponse.hasError()) { 
							long[] offsets = offsetResponse.offsets(topic, part.partitionId()); 
							retVals.put(topicAndPartition, offsets[0]);
						}
					}
				}
			}
			simpleConsumer.close();
		}
		return retVals;
	}
}
public class GetTopicOffsetFromZookeeper {
	
	public static Map<TopicAndPartition,Long> getConsumerOffsets(String zkServers,String groupID, String topic) { 
		Map<TopicAndPartition,Long> retVals = new HashMap<TopicAndPartition,Long>();
		
		ObjectMapper objectMapper = new ObjectMapper();
		CuratorFramework  curatorFramework = CuratorFrameworkFactory.builder()
				.connectString(zkServers).connectionTimeoutMs(1000)
				.sessionTimeoutMs(10000).retryPolicy(new RetryUntilElapsed(1000, 1000)).build();
		
		curatorFramework.start();
		
		try{
			String nodePath = "/consumers/"+groupID+"/offsets/" + topic;
			if(curatorFramework.checkExists().forPath(nodePath)!=null){
				List<String> partitions=curatorFramework.getChildren().forPath(nodePath);
				for(String partiton:partitions){
					int partitionL=Integer.valueOf(partiton);
					Long offset=objectMapper.readValue(curatorFramework.getData().forPath(nodePath+"/"+partiton),Long.class);
					TopicAndPartition topicAndPartition=new TopicAndPartition(topic,partitionL);
					retVals.put(topicAndPartition, offset);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		curatorFramework.close();
		
		return retVals;
	} 
	
	
	public static void main(String[] args) {
		Map<TopicAndPartition, Long> consumerOffsets = getConsumerOffsets("node3:2181,node4:2181,node5:2181","zhy","mytopic");
		Set<Entry<TopicAndPartition, Long>> entrySet = consumerOffsets.entrySet();
		for(Entry<TopicAndPartition, Long> entry : entrySet) {
			TopicAndPartition topicAndPartition = entry.getKey();
			String topic = topicAndPartition.topic();
			int partition = topicAndPartition.partition();
			Long offset = entry.getValue();
			System.out.println("topic = "+topic+",partition = "+partition+",offset = "+offset);
		}
	}
}
public class ProjectUtil {
	/**
	 * 使用log4j配置打印日志
	 */
	static final Logger logger = Logger.getLogger(UseZookeeperManageOffset.class);
	/**
	 * 加载配置的log4j.properties,默认读取的路径在src下,如果将log4j.properties放在别的路径中要手动加载
	 */
	public static void LoadLogConfig() {
		PropertyConfigurator.configure("d:/eclipse4.7WS/SparkStreaming_Kafka_Manage/resource/log4j.properties"); 
	}
	
	/**
	 * 加载配置文件
	 * 需要将放config.properties的目录设置成资源目录
	 * @return
	 */
	public static Properties loadProperties() {

        Properties props = new Properties();
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
        if(null != inputStream) {
            try {
                props.load(inputStream);
            } catch (IOException e) {
            	logger.error(String.format("Config.properties file not found in the classpath"));
            }
        }
        return props;

    }
	
	public static void main(String[] args) {
		Properties props = loadProperties();
		String value = props.getProperty("hello");
		System.out.println(value);
	}
}
public class SparkStreamingDirect {
	public static JavaStreamingContext getStreamingContext(Map<TopicAndPartition, Long> topicOffsets, final String groupID){
		SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("SparkStreamingOnKafkaDirect");
		conf.set("spark.streaming.kafka.maxRatePerPartition", "10");
        JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
//        jsc.checkpoint("/checkpoint");
        Map<String, String> kafkaParams = new HashMap<String, String>();
        kafkaParams.put("metadata.broker.list","node1:9092,node2:9092,node3:9092");
//        kafkaParams.put("group.id","MyFirstConsumerGroup");

        for(Map.Entry<TopicAndPartition,Long> entry:topicOffsets.entrySet()){
    		System.out.println(entry.getKey().topic()+"\t"+entry.getKey().partition()+"\t"+entry.getValue());
        }

        JavaInputDStream<String> message = KafkaUtils.createDirectStream(
			jsc,
	        String.class,
	        String.class, 
	        StringDecoder.class,
	        StringDecoder.class, 
	        String.class,
	        kafkaParams,
	        topicOffsets, 
	        new Function<MessageAndMetadata<String,String>,String>() {
	            /**
				 * 
				 */
				private static final long serialVersionUID = 1L;
	
				public String call(MessageAndMetadata<String, String> v1)throws Exception {
	                return v1.message();
	            }
	        }
		);

        final AtomicReference<OffsetRange[]> offsetRanges = new AtomicReference<>();

        JavaDStream<String> lines = message.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
            public JavaRDD<String> call(JavaRDD<String> rdd) throws Exception {
              OffsetRange[] offsets = ((HasOffsetRanges) rdd.rdd()).offsetRanges();
              offsetRanges.set(offsets);
              return rdd;
            }
          }
        );

        message.foreachRDD(new VoidFunction<JavaRDD<String>>(){
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
            public void call(JavaRDD<String> t) throws Exception {

                ObjectMapper objectMapper = new ObjectMapper();

                CuratorFramework  curatorFramework = CuratorFrameworkFactory.builder()
                        .connectString("node3:2181,node4:2181,node5:2181").connectionTimeoutMs(1000)
                        .sessionTimeoutMs(10000).retryPolicy(new RetryUntilElapsed(1000, 1000)).build();

                curatorFramework.start();

                for (OffsetRange offsetRange : offsetRanges.get()) {
                	long fromOffset = offsetRange.fromOffset();
                	long untilOffset = offsetRange.untilOffset();
                	final byte[] offsetBytes = objectMapper.writeValueAsBytes(offsetRange.untilOffset());
                    String nodePath = "/consumers/"+groupID+"/offsets/" + offsetRange.topic()+ "/" + offsetRange.partition();
                    System.out.println("nodePath = "+nodePath);
                    System.out.println("fromOffset = "+fromOffset+",untilOffset="+untilOffset);
                    if(curatorFramework.checkExists().forPath(nodePath)!=null){
                        curatorFramework.setData().forPath(nodePath,offsetBytes);
                    }else{
                        curatorFramework.create().creatingParentsIfNeeded().forPath(nodePath, offsetBytes);
                    }
                }

                curatorFramework.close();
            }

        });

        lines.print();

        return jsc;
    }
}
### set log level [DEBUG,INFO,WARN,ERROR,FATAL]###
log4j.rootLogger=INFO,stdout,logfile  

### Output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern = [ %p ] - [ %l ] %m%n

### Output to the log file ###
log4j.appender.logfile = org.apache.log4j.RollingFileAppender  
log4j.appender.logfile.File = ./log/log4j.log  
log4j.appender.logfile.MaxFileSize = 512KB  
log4j.appender.logfile.MaxBackupIndex = 3  
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [ %p ] - [ %l ] %m%n

猜你喜欢

转载自blog.csdn.net/qq_33283652/article/details/86178417