使用websocket与redis实现主动推送数据(附配置)

使用websocket与redis实现主动推送数据(附配置)

第一次写博客,写的不好,将就看

先介绍一下整体项目,有一个数据接收服务器,一个数据展示服务器,所以使用redis来推送数据,本博客是介绍如何使用websocket与redis来实现主动的数据推送,框架部分使用Springboot,数据库使用mysql,数据库中间件使用ShardingSphere(顺便吐槽一下ShardingSpaere不支持子查询的问题),,本文中会把功能如何实现,配置,思路等都写出来,也是防止自己时间长忘记了。

前段获取数据的几种方式

前端主动获取

一种就是前段主动获取数据,这种方式有很多,axios,jq,dwr,等等,有很多,我就不一一说明了,这种获取方式的特点就是后端被动(思想转变过来),只能由前端发起请求,后端被动的返回数据,平常情况下很好使,但是遇到需要实时获取数据的就有点麻烦,ajax虽然可以实时获取,但他也是采用寻轮的方式,通过不断的往后端发送请求来返回数据,虽然缓存的存在,可以省去一点性能消耗,但是对后端也是一种很大的开销,特别是数据量大,查询时间长的情况下,现在我写的后台就是,ajax广大朋友们应该就有个差不多的认识,不说了。

前端被动获取

还一种就是前端被动获取数据,这种方式我主要使用的的websocket来实现,特备适合于数据推送,节约性能消耗,websocket,采用ws协议,跟普通的http,https有很大的不同,当然ws协议也就安全的wss,对协议感兴趣的可以自行百度。废话不多少,上代码。
1.webscoket前端代码,数据是从thymleaf里面获取的,里面掺杂了我自己的代码逻辑,等下会贴出精简部分

yml里的webscoket路径配置下面代码会用到

#你自己的websocket路径
webscoketUrl:
  url: ws://*.*.*.com/websocket
  

`

`

前端精简websocket代码

<script type="text/javascript">
	    //判断当前浏览器是否支持WebSocket
	    if ('WebSocket' in window) {
	    //路径里的ws不要换,如果是安全协议可以使用wss,
	    //顺带说明ngrok跟nginx需要单独配
	    //路径写你websocket的路径,后面会有
	        websocket = new WebSocket("ws://localhost:8080/websocket");
	        //连接发生错误的回调方法
	        websocket.onerror = function () {
	            setMessageInnerHTML("WebSocket连接发生错误");
	        };
 
	        //连接成功建立的回调方法
	        websocket.onopen = function () {
	            setMessageInnerHTML("WebSocket连接成功");
	        }
 
	        //接收到消息的回调方法
	        websocket.onmessage = function (event) {
	            setMessageInnerHTML(event.data);
	        }
 
	        //连接关闭的回调方法
	        websocket.onclose = function () {
	            setMessageInnerHTML("WebSocket连接关闭");
	        }
 
	        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
	        window.onbeforeunload = function () {
	            closeWebSocket();
	        }
 
	       
	    }
	    else {
	        alert('当前浏览器 Not support websocket')
	    }
    };
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '
'
; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script>

前端到这就结束了,开始后端配置,定义配置类

package com.zkjh.subservice_web.iot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

package com.zkjh.subservice_web.iot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
//前端路径
@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class WebSocketServer {

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;


    /**
     * 收到客户端消息后调用的方法
     * 在此处已预留可以添加需要推送的硬件信息 目前来看项目不需要选择推送温湿度,浓度,压强等数据
     * @param message 客户端发送过来的消息
     * @functionname onMassage
     * @author zhp
     * */
    @OnMessage
    public void onMessage(String message, Session session) {
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (session) {
            this.session.getBasicRemote().sendText(message);
        }
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) {
        log.info("推送消息到窗口");
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定全部推送
                    item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }
    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket发生错误" + error);
        error.printStackTrace();
    }
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        log.info("websocket:有新连接开始监听!");
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        log.info("连接关闭!");
    }

}

websocket后端配置结束

redis配置

package com.zkjh.subservice_web.iot.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

封装从redis获取数据的工具类

package com.zkjh.subservice_web.iot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RedisUtils(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //================================Map=================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object,Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String,Object> map){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String,Object> map, long time){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value,long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item){
        redisTemplate.opsForHash().delete(key,item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item){
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param item 项
     * @param by 要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item,-by);
    }

    //============================set=============================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object...values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key,long time,Object...values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if(time>0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object ...values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index,Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key,long count,Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

redis的properties配置

########redis##########
# Redis默认数据库索引
spring.redis.database=0
# Redis数据库连接路径
#spring.redis.host=127.0.0.1
spring.redis.host=192.168.2.155
# Redis端口号
spring.redis.port=6379
# Redis密码
spring.redis.password=
# 最大超时时间
spring.redis.timeout=30000

从redis消息队列中读取消息

package com.zkjh.subservice_web.iot.RedisMessageListener;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;


@Configuration
public class RedisMessageListener{

    //不同的频道名
    private static final  String channel = "Battery";
    private static final  String channel2 = "CH4";
    private static final  String channel3 = "Humiture";
    private static final  String channel4 = "Location";
    private static final  String channel5 = "Pressure";
    private static final  String channel6 = "SignalIntensity";
    private static final  String channel7 = "Warn";
    private static final  String channeTimeOut = "__key*@0__:expired";

    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     * @param connectionFactory
     * @param listenerAdapter
     * @return
     */
    @Bean//相当于xml中的bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter, MessageListenerAdapter listenerAdapter2,MessageListenerAdapter listenerAdapter3,
                                            MessageListenerAdapter listenerAdapter4,MessageListenerAdapter listenerAdapter5,MessageListenerAdapter listenerAdapter6,
                                            MessageListenerAdapter listenerAdapter7,MessageListenerAdapter listenerAdapterTimeOut) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //listenerAdapter的通道
        container.addMessageListener(listenerAdapter, new PatternTopic(RedisMessageListener.channel));
        container.addMessageListener(listenerAdapter2, new PatternTopic(RedisMessageListener.channel2));
        container.addMessageListener(listenerAdapter3, new PatternTopic(RedisMessageListener.channel3));
        container.addMessageListener(listenerAdapter4, new PatternTopic(RedisMessageListener.channel4));
        container.addMessageListener(listenerAdapter5, new PatternTopic(RedisMessageListener.channel5));
        container.addMessageListener(listenerAdapter6, new PatternTopic(RedisMessageListener.channel6));
        container.addMessageListener(listenerAdapter7, new PatternTopic(RedisMessageListener.channel7));
        container.addMessageListener(listenerAdapterTimeOut, new PatternTopic(RedisMessageListener.channeTimeOut));
        return container;
    }

    /**
     * 消息监听器适配器,绑定消息处理器,利用反射技术调用消息处理器的业务方法
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    MessageListenerAdapter listenerAdapter2(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage2");
    }

    @Bean
    MessageListenerAdapter listenerAdapter3(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage3");
    }
    @Bean
    MessageListenerAdapter listenerAdapter4(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage4");
    }
    @Bean
    MessageListenerAdapter listenerAdapter5(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage5");
    }
    @Bean
    MessageListenerAdapter listenerAdapter6(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage6");
    }
    @Bean
    MessageListenerAdapter listenerAdapter7(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage7");
    }
    /**redis 读取内容的template */
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    /**
     * 监听redis超时
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapterTimeOut(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessageTimeOut");
    }
}

消息监听器配置完成,写发送消息的类

package com.zkjh.subservice_web.iot.RedisMessageListener;

import com.alibaba.fastjson.JSONObject;
import com.zkjh.subservice_web.iot.config.WebSocketServer;
import com.zkjh.subservice_web.iot.nb_iot.api.Authorization.AppAuthorization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;


@Component
@Slf4j
public class MessageReceiver {

    @Autowired
    private AppAuthorization appAuthorization;

//    String Battery;
//    String CH4;
//    String Humiture;
//    String Location;
//    String Pressure;
//    String SignalIntensity;
//    String Warn;
    WebSocketServer webSocketServer = new WebSocketServer();
    /**Battery*/
    public void receiveMessage(String message){
        System.out.println("Battery:"+message);
//        Battery = message;
        List list = new ArrayList();
        list.add("Battery");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("Battery Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }

    /**CH4*/
    public void receiveMessage2(String message){
        System.out.println("CH4:"+message);
        //CH4.add(message);
        List list = new ArrayList();
        list.add("CH4");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("CH4 Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }
    /**Humiture*/
    public void receiveMessage3(String message){
        System.out.println("Humiture:"+message);
        //Humiture.add(message);
        List list = new ArrayList();
        list.add("Humiture");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("Humiture Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }
    /**Location*/
    public void receiveMessage4(String message){
        System.out.println("Location:"+message);
        //Location.add(message);
        List list = new ArrayList();
        list.add("Location");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("Location Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }
    /**Pressure*/
    public void receiveMessage5(String message){
        System.out.println("Pressure:"+message);
        //Pressure.add(message);
        List list = new ArrayList();
        list.add("Pressure");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("Pressure Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }
    /**SignalIntensity*/
    public void receiveMessage6(String message){
        System.out.println("SignalIntensity:"+message);
        //SignalIntensity.add(message);
        List list = new ArrayList();
        list.add("SignalIntensity");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("SignalIntensity Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }
    /**Warn*/
    public void receiveMessage7(String message){
        System.out.println("Warn:"+message);
        //Warn.add(message);
        List list = new ArrayList();
        list.add("Warn");
        list.add(message.replaceAll("\\\\",""));
        String json = JSONObject.toJSONString(list);
        log.info("Warn Data is loading out");
        try {
            webSocketServer.sendInfo(json);
        } catch (Exception e) {
            log.info("消息发送失败!IO异常"+e);
            e.printStackTrace();
        }
        //return message;
    }

    public void receiveMessageTimeOut(String message){
        if(message.equals("accessToken")){
            // 1小时超时
            // 调用刷新accessToken接口
            log.info("accessToken超时");
            try {
                appAuthorization.getRefreshToken();
            } catch (Exception e) {
                log.info("accessToken超时:刷新accessToken失败!");
                e.printStackTrace();
            }
        }
        if( message.equals("refreshToken")){
            // 1天超时
            // 调用刷新鉴权接口获取 accessToken 和 refreshToken
            log.info("refreshToken超时");
            try {
                appAuthorization.getAppAuthorizationInfo();
            } catch (Exception e) {
                log.info("refreshToken超时:重新获取accessToken失败!");
                e.printStackTrace();
            }
        }
    }
}

至此接收端所有配置完成,最后一步还需要主动发送数据部分,因为我的这项目还有一个数据接收服务器,所以往消息队列中存数据的点在另外一个服务器,其中redis的配置都一样,相关代码都已经去掉,只填了一些测试数据

package com.zkjh.znwlw_service.service.redisPublish;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class Publish {

    @Autowired
    //这个地方需要配置redis,领起一个项目配置都一样,另起一个项目配一下 就行
    private RedisTemplate<String, Object> redisTemplate;
    public void sendMessage(String aa,String bb) {
        String channel = "Battery";//在哪个频道里发数据
        String msg = "{" +//发什么数据
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"batteryLevel\":\"3\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
//        JSONObject jsonObject = JSONObject.parseObject(msg);
//        String json = JSON.toJSONString(jsonObject);
//        Map map = new HashMap();
//        map.put(channel,jsonObject);
        redisTemplate.convertAndSend(channel, msg);

        String CH4 = "CH4";
        String msg1 = "{" +
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"concentration\":\"3\"," +
                "\"faultCodeNum\":\"01\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject1 = JSONObject.parseObject(msg1);
        redisTemplate.convertAndSend(CH4, msg1);

        String Humiture = "Humiture";
        String msg2 = "{" +
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"temp\":\"0.2\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject2 = JSONObject.parseObject(msg2);
        redisTemplate.convertAndSend(Humiture, msg2);

        String Location = "Location";
        String msg3 = "{" +
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"latitude\":\"31.244163\"," +
                "\"longtitude\":\"119.077009\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject3 = JSONObject.parseObject(msg3);
        redisTemplate.convertAndSend(Location, msg3);

        String Pressure = "Pressure";
        String msg4 ="{" +
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"atmoPressure\":\"70.51\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject4 = JSONObject.parseObject(msg4);
        redisTemplate.convertAndSend(Pressure, msg4);

        String SignalIntensity = "SignalIntensity";
        String msg5 = "{"+
                "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                "\"rssi\":\"8\"," +
                "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject5 = JSONObject.parseObject(msg5);
        redisTemplate.convertAndSend(SignalIntensity, msg5);

        String Warn = "Warn";
        String msg6 = "{"+
                        "\"deviceId\":\"e9584627ad1711e9910500d861316026\"," +
                        "\"gatewayId\":\"8280c8ec-cbb9-4385-98b0-96cbebcded1d\"," +
                        "\"toppleFall\":\"0\"," +
                        "\"waterPenetration\":\"5\"," +
                        "\"EventTime\":\"2019-07-23 21:15:55\"" +
                "}";
        //JSONObject jsonObject6 = JSONObject.parseObject(msg6);
        redisTemplate.convertAndSend(Warn, msg6);
    }
}

调用sendMessage方法,发送数据,测试成功,至此,使用websocket+redis实现主动的数据推送完成。码字不易,不喜勿喷,手动滑稽脸

你可能感兴趣的:(redis,websocket,消息队列,数据推送)