java - netty4,服务端向客户端主动发消息怎么把channel存储到redis缓存中?
阿神
阿神 2017-04-18 10:36:26
0
1
1851
阿神
阿神

闭关修行中......

reply all(1)
迷茫

This is roughly what we do in our project:
Whether you write your own data structure or use Jedis, there is probably a structure similar to Map.

  • Create a Bean to represent the session, let’s call it Session here.

  • Reference netty’s Channel in Session.

  • Put it into redis when channelActive.

  • If necessary, you can use channel.id().asLongText()channel.id().asShortText() as the unique identifier of the Session

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    //可以将channel.id().asLongText()或channel.id().asShortText()作为Session的ID
    Session session = Session.buildSession(ctx.channel());
    //Session存入Redis
    pushSession2Redis(session);
    logger.info("终端连接:{}", session);
}

Session.java

import java.net.SocketAddress;
import io.netty.channel.Channel;

public class Session {
    //Session的唯一标识
    private String id;
    //和Session相关的channel,通过它向客户端回送数据
    private Channel channel = null;
    //上次通信时间
    private long lastCommunicateTimeStamp = 0l;

    //快速构建一个新的Session    
    public static Session buildSession(Channel channel) {
        Session session = new Session();
        session.setChannel(channel);

        //此处暂且使用netty生成的类似UUID的字符串,来标识一个session
        session.setId(channel.id().asLongText());
        session.setLastCommunicateTimeStamp(System.currentTimeMillis());
        return session;
    }

    // getter,setter
}
public class SessionManager{

    //将Session放入redis
    public void pushSession2Redis(Session  session){
        //这里就不用我说了吧
        //不知道你自己用的redis客户端是什么
        //调用客户端(比如Jedis)的API把session放到你自己的数据结构不就行了
    }
    
    //从redis获取指定session
    public Session findById(String sessionId){
        return null;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template