一、websocket简介
html5规范在传统的web交互基础上为我们带来了众多的新特性,随着web技术被广泛用于web app的开发,这些新特性得以推广和使用,而websocket作为一种新的web通信技术具有巨大意义。websocket是html5新增的协议,它的目的是在浏览器和服务器之间建立一个不受限的双向通信的通道,比如说,服务器可以在任意时刻发送消息给浏览器。支持双向通信。
二、websocket通信原理及机制
websocket是基于浏览器端的web技术,那么它的通信肯定少不了http,websocket本身虽然也是一种新的应用层协议,但是它也不能够脱离http而单独存在。具体来讲,我们在客户端构建一个websocket实例,并且为它绑定一个需要连接到的服务器地址,当客户端连接服务端的时候,会向服务端发送一个消息报文
三、websocket特点和优点
1、支持双向通信,实时性更强。
2、更好的二进制支持。
3、较少的控制开销。连接创建后,ws客户端、服务端进行数据交换时,协议控制的数据包头部较小。在不包含头部的情况下,服务端到客户端的包头只有2~10字节(取决于数据包长度),客户端到服务端的的话,需要加上额外的4字节的掩码。而http协议每次通信都需要携带完整的头部。
4、支持扩展。ws协议定义了扩展,用户可以扩展协议,或者实现自定义的子协议。(比如支持自定义压缩算法等)
5、建立在tcp协议之上,服务端实现比较容易
6、数据格式比较轻量,性能开销小,通信效率高
7、和http协议有着良好的兼容性,默认端口是80和443,并且握手阶段采用http协议,因此握手的时候不容易屏蔽,能通过各种的http代理
四、websocket心跳机制
在使用websocket过程中,可能会出现网络断开的情况,比如信号不好,或者网络临时性关闭,这时候websocket的连接已经断开,而浏览器不会执行websocket 的 onclose方法,我们无法知道是否断开连接,也就无法进行重连操作。如果当前发送websocket数据到后端,一旦请求超时,onclose便会执行,这时候便可进行绑定好的重连操作。
心跳机制是每隔一段时间会向服务器发送一个数据包,告诉服务器自己还活着,同时客户端会确认服务器端是否还活着,如果还活着的话,就会回传一个数据包给客户端来确定服务器端也还活着,否则的话,有可能是网络断开连接了。需要重连~
五、在后端spring boot 和前端vue中如何建立通信
1、在spring boot 中 pom.xml中添加 websocket依赖
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-websocket</artifactid>
</dependency>
2、创建 websocketconfig.java 开启websocket支持
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.server.standard.serverendpointexporter;
/**
* 开启websocket支持
*
*/
@configuration
public class websocketconfig {
@bean
public serverendpointexporter serverendpointexporter() {
return new serverendpointexporter();
}
}
3、创建 websocketserver.java 链接
package com.mes.dispatch.socket;
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.lang3.stringutils;
import org.springframework.stereotype.component;
import javax.websocket.*;
import javax.websocket.server.pathparam;
import javax.websocket.server.serverendpoint;
import java.io.ioexception;
import java.util.hashmap;
import java.util.iterator;
import java.util.concurrent.concurrenthashmap;
/** @author: best_liu
* @description:websocket服务
* @date: 13:05 2023/8/31
* @param
* @return
**/
@serverendpoint("/websocket/processsocket/{userid}")
@slf4j
@component
public class websocketserver {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlinecount = 0;
/**
* concurrent包的线程安全set,用来存放每个客户端对应的mywebsocket对象。
*/
private static concurrenthashmap<string, websocketserver> websocketmap = new concurrenthashmap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private session session;
/**
* 接收userid
*/
private string userid = "";
/**
* 连接建立成功调用的方法
*/
@onopen
public void onopen(session session, @pathparam("userid") string userid) {
this.session = session;
this.userid = userid;
if (websocketmap.containskey(userid)) {
websocketmap.remove(userid);
//加入set中
} else {
websocketmap.put(userid, this);
//加入set中
addonlinecount();
//在线数加1
}
log.info("用户连接:" + userid + ",当前在线人数为:" + getonlinecount());
try {
hashmap<object, object> map = new hashmap<>();
map.put("key", "连接成功");
sendmessage(json.tojsonstring(map));
} catch (ioexception e) {
log.error("用户:" + userid + ",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@onclose
public void onclose() {
if (websocketmap.containskey(userid)) {
websocketmap.remove(userid);
//从set中删除
subonlinecount();
}
log.info("用户退出:" + userid + ",当前在线人数为:" + getonlinecount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@onmessage
public void onmessage(string message, session session) {
log.info("用户消息:" + userid + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (stringutils.isnotblank(message)) {
try {
//解析发送的报文
jsonobject jsonobject = jsonobject.parseobject(message);
//追加发送人(防止串改)
jsonobject.put("fromuserid", this.userid);
string fromuserid = jsonobject.getstring("fromuserid");
//传送给对应touserid用户的websocket
if (stringutils.isnotblank(fromuserid) && websocketmap.containskey(fromuserid)) {
websocketmap.get(fromuserid).sendmessage(jsonobject.tojsonstring());
//自定义-业务处理
// devicelocalthread.paramdata.put(jsonobject.getstring("group"),jsonobject.tojsonstring());
} else {
log.error("请求的userid:" + fromuserid + "不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
} catch (exception e) {
e.printstacktrace();
}
}
}
/**
* 发生错误时候
*
* @param session
* @param error
*/
@onerror
public void onerror(session session, throwable error) {
log.error("用户错误:" + this.userid + ",原因:" + error.getmessage());
error.printstacktrace();
}
/**
* 实现服务器主动推送
*/
public void sendmessage(string message) throws ioexception {
//加入线程锁
synchronized (session) {
try {
//同步发送信息
this.session.getbasicremote().sendtext(message);
} catch (ioexception e) {
log.error("服务器推送失败:" + e.getmessage());
}
}
}
/** @author: best_liu
* @description:发送自定义消息
* @date: 13:01 2023/8/31
* @param [message, touserid]
* @return void
**/
public static void sendinfo(string message, string touserid) throws ioexception {
//如果userid为空,向所有群体发送
if (stringutils.isempty(touserid)) {
//向所有用户发送信息
iterator<string> itera = websocketmap.keyset().iterator();
while (itera.hasnext()) {
string keys = itera.next();
websocketserver item = websocketmap.get(keys);
item.sendmessage(message);
}
}
//如果不为空,则发送指定用户信息
else if (websocketmap.containskey(touserid)) {
websocketserver item = websocketmap.get(touserid);
item.sendmessage(message);
} else {
log.error("请求的userid:" + touserid + "不在该服务器上");
}
}
public static synchronized int getonlinecount() {
return onlinecount;
}
public static synchronized void addonlinecount() {
websocketserver.onlinecount++;
}
public static synchronized void subonlinecount() {
websocketserver.onlinecount--;
}
public static synchronized concurrenthashmap<string, websocketserver> getwebsocketmap() {
return websocketserver.websocketmap;
}
}
4、创建一个测试调用websocket发送消息 timersocketmessage.java (用定时器发送推送消息
import org.springframework.scheduling.annotation.enablescheduling;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
import java.util.hashmap;
import java.util.map;
@component
@enablescheduling
public class timersocketmessage {
/**
* 推送消息到前台
*/
@scheduled(cron = "*/5 * * * * * ")
public void socketmessage(){
simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
map<string, object> maps = new hashmap<>();
maps.put("type", "sendmessage");
maps.put("data", sdf.format(new date()));
websocketserver.sendinfo(maps);
}
}
5、在vue中创建和后端 websocket服务的连接并建立心跳机制。
<template>
<div>
<el-row :gutter="$ui.layout.gutter.g10">
<el-col :span="$ui.layout.span.one" style="background-color: #ffffff; padding: 10px;">
<el-form ref="form" :model="form" label-width="80px" size="small" :inline="true">
<el-form-item label="生成数量">
<el-input-number v-model="form.number" :min="1" :max="999" label="描述文字" />
</el-form-item>
<el-form-item label="数值范围">
<el-input-number v-model="form.start" :min="1" :max="9999999999" label="描述文字" /> ~
<el-input-number v-model="form.end" :min="1" :max="9999999999" label="描述文字" />
</el-form-item>
<el-form-item>
<el-button size="mini" type="primary" @click="spawn">生成</el-button>
</el-form-item>
</el-form>
</el-col>
</el-row>
<h1> websocket 消息推送测试:{{data}}</h1>
</div>
</template>
<script>
export default {
name: 'index',
data() {
return {
form: {
number: 1,
start: 1,
end: 100
},
data:0,
timeout: 28 * 1000,//30秒一次心跳
timeoutobj: null,//心跳心跳倒计时
servertimeoutobj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
websocket: null,
}
},
created () {
// 初始化websocket
this.initwebsocket()
},
methods: {
spawn() {
},
//socket--start
initwebsocket() {
let url = 'ws://localhost/dev-api/process/websocket/processsocket/zkawsystem'
this.websocket = new websocket(url)
// 连接错误
this.websocket.onerror = this.seterrormessage
// 连接成功
this.websocket.onopen = this.setonopenmessage
// 收到消息的回调
this.websocket.onmessage = this.setonmessagemessage
// 连接关闭的回调
this.websocket.onclose = this.setonclosemessage
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload
},
reconnect() { // 重新连接
if (this.lockreconnect) return;
this.lockreconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
this.timeoutnum && cleartimeout(this.timeoutnum);
this.timeoutnum = settimeout(() => {
//新连接
this.initwebsocket();
this.lockreconnect = false;
}, 5000);
},
reset() { // 重置心跳
// 清除时间
cleartimeout(this.timeoutobj);
cleartimeout(this.servertimeoutobj);
// 重启心跳
this.start();
},
start() { // 开启心跳
this.timeoutobj && cleartimeout(this.timeoutobj);
this.servertimeoutobj && cleartimeout(this.servertimeoutobj);
this.timeoutobj = settimeout(() => {
// 这里发送一个心跳,后端收到后,返回一个心跳消息,
if (this.websocket && this.websocket.readystate == 1) { // 如果连接正常
let actions = { "heartbeat": "12345" };
this.websocketsend(json.stringify(actions));
} else { // 否则重连
this.reconnect();
}
this.servertimeoutobj = settimeout(() => {
//超时关闭
this.websocket.close();
}, this.timeout);
}, this.timeout)
},
setonmessagemessage(event) {
let obj = json.parse(event.data);
console.log("obj", obj)
switch (obj.type) {
case 'heartbeat':
//收到服务器信息,心跳重置
this.reset();
break;
case 'sendmessage':
this.data = obj.data
console.log("接收到的服务器消息:", obj.data)
}
},
seterrormessage() {
//重连
this.reconnect();
console.log("websocket连接发生错误" + ' 状态码:' + this.websocket.readystate)
},
setonopenmessage() {
//开启心跳
this.start();
console.log("websocket连接成功" + ' 状态码:' + this.websocket.readystate)
},
setonclosemessage() {
//重连
this.reconnect();
console.log("websocket连接关闭" + ' 状态码:' + this.websocket.readystate)
},
onbeforeunload() {
this.closewebsocket();
},
//websocket发送消息
websocketsend(messsage) {
this.websocket.send(messsage)
},
closewebsocket() { // 关闭websocket
this.websocket.close()
},
//socket--end
}
}
</script>
6、启动项目开始测试结果
7、vue文件连接websocket的url地址要拼接 context-path: /demo
六、websocket不定时出现1005错误
后台抛出异常如下:
operator called default onerrordropped
reactor.core.exceptions$errorcallbacknotimplemented: java.lang.illegalargumentexception: websocket close status code does not comply with rfc-6455: 1005
caused by: java.lang.illegalargumentexception: websocket close status code does not comply with rfc-6455: 1005
分析原因是:
spring cloud gateway 转发请求无法监听到 close 事件 没有收到预期的状态码
解决方案:
在gateway进行请求拦截
代码如下:
package com.mes.gateway.filter;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.objectprovider;
import org.springframework.cloud.gateway.filter.gatewayfilterchain;
import org.springframework.cloud.gateway.filter.globalfilter;
import org.springframework.cloud.gateway.filter.headers.httpheadersfilter;
import org.springframework.cloud.gateway.support.serverwebexchangeutils;
import org.springframework.core.ordered;
import org.springframework.http.httpheaders;
import org.springframework.stereotype.component;
import org.springframework.util.stringutils;
import org.springframework.web.reactive.socket.closestatus;
import org.springframework.web.reactive.socket.websockethandler;
import org.springframework.web.reactive.socket.websocketmessage;
import org.springframework.web.reactive.socket.websocketsession;
import org.springframework.web.reactive.socket.client.websocketclient;
import org.springframework.web.reactive.socket.server.websocketservice;
import org.springframework.web.server.serverwebexchange;
import org.springframework.web.util.uricomponentsbuilder;
import reactor.core.publisher.mono;
import java.net.uri;
import java.util.*;
/**
* @author: best_liu
* @description:解决websocket关闭异常 问题
* @desc websocket客户端主动断开连接,网关服务报错1005
* @date create in 11:15 2023/10/25
* @modified by:
*/
@component
public class customwebsocketroutingfilter implements globalfilter, ordered {
private static final logger log = loggerfactory.getlogger(authfilter.class);
//sec-websocket protocol
public static final string sec_websocket_protocol = "sec-websocket-protocol";
//sec-websocket header
public static final string sec_websocket_header = "sec-websocket";
//http header schema
public static final string header_upgrade_websocket = "websocket";
public static final string header_upgrade_http = "http";
public static final string header_upgrade_https = "https";
private final websocketclient websocketclient;
private final websocketservice websocketservice;
private final objectprovider<list<httpheadersfilter>> headersfiltersprovider;
// 不直接使用 headersfilters 用该变量代替
private volatile list<httpheadersfilter> headersfilters;
public customwebsocketroutingfilter(websocketclient websocketclient, websocketservice websocketservice, objectprovider<list<httpheadersfilter>> headersfiltersprovider) {
this.websocketclient = websocketclient;
this.websocketservice = websocketservice;
this.headersfiltersprovider = headersfiltersprovider;
}
/* for testing */
//http请求转为ws请求
static string converthttptows(string scheme) {
scheme = scheme.tolowercase();
return "http".equals(scheme) ? "ws" : "https".equals(scheme) ? "wss" : scheme;
}
@override
public int getorder() {
// before nettyroutingfilter since this routes certain http requests
//修改了这里 之前是-1 降低优先级
return ordered.lowest_precedence - 2;
}
@override
public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
changeschemeifiswebsocketupgrade(exchange);
uri requesturl = exchange.getrequiredattribute(serverwebexchangeutils.gateway_request_url_attr);
string scheme = requesturl.getscheme();
if (serverwebexchangeutils.isalreadyrouted(exchange) || (!"ws".equals(scheme) && !"wss".equals(scheme))) {
return chain.filter(exchange);
}
serverwebexchangeutils.setalreadyrouted(exchange);
httpheaders headers = exchange.getrequest().getheaders();
httpheaders filtered = httpheadersfilter.filterrequest(getheadersfilters(), exchange);
list<string> protocols = getprotocols(headers);
return this.websocketservice.handlerequest(exchange, new proxywebsockethandler(requesturl, this.websocketclient, filtered, protocols));
}
/* for testing */
//获取请求头里的协议信息
list<string> getprotocols(httpheaders headers) {
list<string> protocols = headers.get(sec_websocket_protocol);
if (protocols != null) {
arraylist<string> updatedprotocols = new arraylist<>();
for (int i = 0; i < protocols.size(); i++) {
string protocol = protocols.get(i);
updatedprotocols.addall(arrays.aslist(stringutils.tokenizetostringarray(protocol, ",")));
}
protocols = updatedprotocols;
}
return protocols;
}
/* for testing */
list<httpheadersfilter> getheadersfilters() {
if (this.headersfilters == null) {
this.headersfilters = this.headersfiltersprovider.getifavailable(arraylist::new);
// remove host header unless specifically asked not to
this.headersfilters.add((headers, exchange) -> {
httpheaders filtered = new httpheaders();
filtered.addall(headers);
filtered.remove(httpheaders.host);
boolean preservehost = exchange.getattributeordefault(serverwebexchangeutils.preserve_host_header_attribute, false);
if (preservehost) {
string host = exchange.getrequest().getheaders().getfirst(httpheaders.host);
filtered.add(httpheaders.host, host);
}
return filtered;
});
this.headersfilters.add((headers, exchange) -> {
httpheaders filtered = new httpheaders();
for (map.entry<string, list<string>> entry : headers.entryset()) {
if (!entry.getkey().tolowercase().startswith(sec_websocket_header)) {
filtered.addall(entry.getkey(), entry.getvalue());
}
}
return filtered;
});
}
return this.headersfilters;
}
static void changeschemeifiswebsocketupgrade(serverwebexchange exchange) {
// 检查版本是否适合
uri requesturl = exchange.getrequiredattribute(serverwebexchangeutils.gateway_request_url_attr);
string scheme = requesturl.getscheme().tolowercase();
string upgrade = exchange.getrequest().getheaders().getupgrade();
// change the scheme if the socket client send a "http" or "https"
if (header_upgrade_websocket.equalsignorecase(upgrade) && (header_upgrade_http.equals(scheme) || header_upgrade_https.equals(scheme))) {
string wsscheme = converthttptows(scheme);
boolean encoded = serverwebexchangeutils.containsencodedparts(requesturl);
uri wsrequesturl = uricomponentsbuilder.fromuri(requesturl).scheme(wsscheme).build(encoded).touri();
exchange.getattributes().put(serverwebexchangeutils.gateway_request_url_attr, wsrequesturl);
if (log.istraceenabled()) {
log.trace("changeschemeto:[" + wsrequesturl + "]");
}
}
}
//自定义websocket处理方式
private static class proxywebsockethandler implements websockethandler {
private final websocketclient client;
private final uri url;
private final httpheaders headers;
private final list<string> subprotocols;
proxywebsockethandler(uri url, websocketclient client, httpheaders headers, list<string> protocols) {
this.client = client;
this.url = url;
this.headers = headers;
if (protocols != null) {
this.subprotocols = protocols;
} else {
this.subprotocols = collections.emptylist();
}
}
@override
public list<string> getsubprotocols() {
return this.subprotocols;
}
@override
public mono<void> handle(websocketsession session) {
return this.client.execute(this.url, this.headers, new websockethandler() {
private closestatus adaptclosestatus(closestatus closestatus) {
int code = closestatus.getcode();
if (code > 2999 && code < 5000) {
return closestatus;
}
switch (code) {
case 1000:
//正常关闭
return closestatus;
case 1001:
//服务器挂了或者页面跳转
return closestatus;
case 1002:
//协议错误
return closestatus;
case 1003:
//收到了不能处理的数据类型
return closestatus;
case 1004:
// 预留关闭状态码
return closestatus.protocol_error;
case 1005:
// 预留关闭状态码 期望收到状态码但是没有收到
return closestatus.protocol_error;
case 1006:
// 预留关闭状态码 连接异常关闭
return closestatus.protocol_error;
case 1007:
//收到的数据与实际的消息类型不匹配
return closestatus;
case 1008:
//收到不符合规则的消息
return closestatus;
case 1009:
//收到太大的不能处理的消息
return closestatus;
case 1010:
//client希望server提供多个扩展,server没有返回相应的扩展信息
return closestatus;
case 1011:
//server遇到不能完成的请求
return closestatus;
case 1012:
// not in rfc6455
// return closestatus.service_restarted;
return closestatus.protocol_error;
case 1013:
// not in rfc6455
// return closestatus.service_overload;
return closestatus.protocol_error;
case 1015:
// 不能进行tls握手 如:server证书不能验证
return closestatus.protocol_error;
default:
return closestatus.protocol_error;
}
}
/**
* send 发送传出消息
* receive 处理入站消息流
* doonnext 对每条消息做什么
* zip 加入流
* then 返回接收完成时完成的mono<void>
*/
@override
public mono<void> handle(websocketsession proxysession) {
mono<void> serverclose = proxysession.closestatus().filter(__ -> session.isopen())
.map(this::adaptclosestatus)
.flatmap(session::close);
mono<void> proxyclose = session.closestatus().filter(__ -> proxysession.isopen())
.map(this::adaptclosestatus)
.flatmap(proxysession::close);
// use retain() for reactor netty
mono<void> proxysessionsend = proxysession
.send(session.receive().doonnext(websocketmessage::retain));
mono<void> serversessionsend = session
.send(proxysession.receive().doonnext(websocketmessage::retain));
// ensure closestatus from one propagates to the other
mono.when(serverclose, proxyclose).subscribe();
// complete when both sessions are done
return mono.zip(proxysessionsend, serversessionsend).then();
}
@override
public list<string> getsubprotocols() {
return customwebsocketroutingfilter.proxywebsockethandler.this.subprotocols;
}
});
}
}
}
七、websocket+redis实现离线消息推送
1、websocket消息机制redis工具类
import com.mes.process.utils.redisutil;
import lombok.extern.slf4j.slf4j;
import org.springframework.stereotype.component;
import java.util.list;
/** @author: best_liu
* @description:websocket消息推送redis工具类
* @date: 13:50 2023/11/28
* @param
* @return
**/
@component
@slf4j
public class websocketredisutil {
/**
* 功能描述:将javabean对象的信息缓存进redis
*
* @param message 信息javabean
* @return 是否保存成功
*/
public static boolean savecachechatmessage(string key, string message) {
//判断key是否存在
if (redisutil.haskey(key)) {
//将javabean对象添加到缓存的list中
long redissize = redisutil.lgetlistsize(key);
system.out.println("redis当前数据条数" + redissize);
long index = redisutil.rightpushvalue(key, message);
system.out.println("redis执行rightpushlist返回值:" + index);
return redissize<index;
} else {
//不存在key时,将chatvo存进缓存,并设置过期时间
// jsonarray jsonarray=new jsonarray();
// jsonarray.add(message);
boolean iscache = redisutil.lset(key, message);
//保存成功,设置过期时间 暂不设置失效时间
if (iscache) {
// redisutil.expire(key, 3l, timeunit.days);
system.out.println("存储成功"+message);
}
return iscache;
}
}
/**
* 功能描述:从缓存中读取信息
*
* @param key 缓存信息的键
* @return 缓存中信息list
*/
public static list<object> getcachechatmessage(string key) {
list<object> chatlist = null;
//判断key是否存在
if (redisutil.haskey(key)) {
chatlist = redisutil.getopsforlist(key);
} else {
log.info("redis缓存中无此键值:" + key);
}
return chatlist;
}
/**
* 功能描述: 在缓存中删除信息
*
* @param key 缓存信息的键
*/
public static void deletecachechatmessage(string key) {
//判断key是否存在
if (redisutil.haskey(key)) {
redisutil.del(key);
}
}
}
2、redisutil普通redis工具类
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
import java.util.arrays;
import java.util.list;
import java.util.concurrent.timeunit;
/** @author: best_liu
* @description:
* @date: 13:50 2023/11/28
* @param
* @return
**/
@slf4j
@component
public class redisutil {
private static redistemplate redistemplate;
@autowired
public void setredistemplate(redistemplate redistemplate) {
redisutil.redistemplate = redistemplate;
}
//=============================common============================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public static boolean expire(string key, long time) {
try {
if (time > 0) {
redistemplate.expire(key, time, timeunit.seconds);
}
return true;
} catch (exception e) {
log.error("设置redis指定key失效时间错误:", e);
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效 失效时间为负数,说明该主键未设置失效时间(失效时间默认为-1)
*/
public static long getexpire(string key) {
return redistemplate.getexpire(key, timeunit.seconds);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false 不存在
*/
public static boolean haskey(string key) {
try {
return redistemplate.haskey(key);
} catch (exception e) {
log.error("redis判断key是否存在错误:", e);
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@suppresswarnings("unchecked")
public static void del(string... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redistemplate.delete(key[0]);
} else {
redistemplate.delete(arrays.aslist(key));
}
}
}
//============================string=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
@suppresswarnings("unchecked")
public static <t> t get(string key) {
return key == null ? null : (t) redistemplate.opsforvalue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public static boolean set(string key, object value) {
try {
redistemplate.opsforvalue().set(key, value);
return true;
} catch (exception e) {
log.error("设置redis缓存错误:", e);
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public static 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;
}
}
// ===================================自定义工具扩展===========================================
/**
* 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 static map<object, object> hmget (string key ) {
// return redistemplate.opsforhash().entries(key);
// }
/**
* 获取hashkey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
// */
// public static list<object> hmget (string key ) {
// return redistemplate.opsforlist().ge;
// }
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public static long lgetlistsize ( string key ) {
try {
return redistemplate.opsforlist().size(key);
} catch (exception e) {
e.printstacktrace();
return 0;
}
}
/**
* 功能描述:在list的右边添加元素
* 如果键不存在,则在执行推送操作之前将其创建为空列表
*
* @param key 键
* @return value 值
* @author renshiwei
* date: 2020/2/6 23:22
*/
public static long rightpushvalue ( string key, object value ) {
return redistemplate.opsforlist().rightpush(key, value);
}
/**
* 功能描述:获取缓存中所有的list key
*
* @param key 键
*/
public static list<object> getopsforlist ( string key) {
return redistemplate.opsforlist().range(key, 0, redistemplate.opsforlist().size(key));
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public static 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 值
* @return
*/
public boolean lset ( string key, list<object> value ) {
try {
redistemplate.opsforlist().rightpushall(key, value);
return true;
} catch (exception e) {
e.printstacktrace();
return false;
}
}
}
3、websocket操作类中加入一下两个方法
方法1:查询是否有离线消息并推送
/**
* 查询是否有离线消息并推送
*
*/
public void cachemessagecontains(string userid){
//是否有暂存的消息,如果有则发送消息
string user = "socket-"+userid.split("-")[0];
list<object> strings = websocketredisutil.getcachechatmessage(user);
if (strings!=null) {
//取出消息列表
list<object> list = strings;
if (list == null) {
log.info("暂无缓存的消息");
}
list.foreach(message -> {
//暂时群发消息
websocketserver item = websocketmap.get(userid);
try {
item.sendmessage(message.tostring());
} catch (ioexception e) {
e.printstacktrace();
}
});
log.info("用户缓存的消息发送成功一共:"+list.size()+"条");
list = null;
websocketredisutil.deletecachechatmessage(user);
}
}
方法2:暂存离线消息
/**
* 暂存离线消息
*
*/
public static void cachemessageput(string userid, string message){
// //把新消息添加到消息列表
if (!stringutils.isempty(message)){
boolean iscache = websocketredisutil.savecachechatmessage("socket-"+userid, message);
if (iscache){
log.info("消息暂存成功" + message);
}else{
log.error("消息暂存失败" + message);
}
}
}
在用户上线的时候调用方法1;在消息推送判断用户不在线是调用方法2.
发表评论