java 集成spring+zookeeper+kafka---消费者

消费者目录结构

java 集成spring+zookeeper+kafka---消费者_第1张图片





MyDecoder类

package com.kd.food.kafka.consumer;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import com.alibaba.fastjson.JSONObject;

import kafka.serializer.Decoder;

public class MyDecoder implements Decoder {

	public MyDecoder() {
		this("UTF8");
	}

	public MyDecoder(final String encoding) {
		final Properties props = new Properties();
		props.put("serializer.encoding", encoding);
	}

	@SuppressWarnings("finally")
	@Override
	public Object fromBytes(byte[] bytes) {
		String content = "";
		JSONObject object = null;
		boolean isbean = true;
		try {
			content = new String(bytes, "UTF-8");
			try {
				object = JSONObject.parseObject(content);
			} catch (Exception e) {
				isbean = false;
			} finally {
				if (isbean) {
					return object;
				} else {
					return content;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return object;
	}

}
 
  

ConsumerMessages类

package com.kd.food.kafka.consumer;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.kd.food.model.UserEquipment;
import com.kd.food.service.UserEquipmentService;

/**
 * 接收消息类
 * @author 25388
 *
 */
public class ConsumerMessages {
	
	@Autowired
	private UserEquipmentService userEquipmentService;
	
	/**
	 * 接受消息方法
	 * @param msgs
	 */
	public void processMessage(Map> msgs) {
		try {

			for (Map.Entry> entry : msgs.entrySet()) {
				Map value = entry.getValue();
				for (Map.Entry entrys : value.entrySet()){
					JSONArray keyArr = (JSONArray) JSONArray.parse(entrys.getValue().toString());
					//JSONArray keyArr =(JSONArray)entrys.getValue();
					JSONObject keyjson = (JSONObject) keyArr.get(0);
					String type = keyjson.getString("type");
					String jsons = keyjson.getString("jsons");
					JSONObject json = JSONObject.parseObject(jsons);
					if("1".equals(type)){//修改设备状态
						String uid = json.getString("uid");
						String status = json.getString("status");
						//封装对象
						UserEquipment userEquipment = new UserEquipment();
						userEquipment.setStatus(status);
						userEquipment.setTerminalId(uid);
						//调用修改设备状态
						userEquipmentService.updateUserEquipmentByMac(userEquipment);
					}
					if("2".equals(type)){//设备解绑所有用户
						String terminalId = json.getString("uid");
						//调用解绑所有用户
						userEquipmentService.deleteUserEquipmentByMac(terminalId);
					}
					
				}
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

kafka-consumer.xml





	
	
		
	
	
	
	
	
	
		
	
	
	
	
	
	
		
			
				smallest
				10485760
				5242880
				1000
			
		
	
	
	
	
	

	
		
			
				
				
			
		
	
>


spring.xml 添加上 kafka-constomer.xml

java 集成spring+zookeeper+kafka---消费者_第2张图片



kafka-consumer.xml

你可能感兴趣的:(spring)