vetrx是基于netty封装的java网络编程框架,比netty开发较为简单,在其基础上提供很多有用功能,能在较短的时间内开发一个http服务器,或其他网络服务。今天我们展示下如何为vertx开发http网关实现分布式session,实现参考spring session。底层使用redis 存贮session
1.SessionStore
vertx读写session 都是通过实现SessionStore实现的,我们可以实现自己的RedisStore 和RedisSession,代码如下
/*
* Copyright 2014 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package com.ly.session;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.VertxContextPRNG;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.sstore.AbstractSession;
import io.vertx.ext.web.sstore.SessionStore;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class RedisSessionStore implements SessionStore {
/**
* Default of how often, in ms, to check for expired sessions
*/
private static final long DEFAULT_REAPER_INTERVAL = 1000;
/**
* Default name for map used to store sessions
*/
private static final String DEFAULT_SESSION_MAP_NAME = "vertx-web.sessions";
private VertxContextPRNG random;
protected Vertx vertx;
private SaveMode saveMode = SaveMode.ON_IMMEDIATE;
public void setSaveMode(SaveMode saveMode) {
this.saveMode = saveMode;
}
private RedisTemplate<String,Object> redisTemplate;
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public Session createSession(long timeout) {
return new RedisDataSessionImpl(random, timeout, DEFAULT_SESSIONID_LENGTH);
}
@Override
public Session createSession(long timeout, int length) {
return new RedisDataSessionImpl(random, timeout, length);
}
@Override
public SessionStore init(Vertx vertx, JsonObject options) {
// initialize a secure random
this.random = VertxContextPRNG.current(vertx);
this.vertx = vertx;
return this;
}
@Override
public long retryTimeout() {
return 0;
}
@Override
public void get(String id, Handler<AsyncResult<Session>> resultHandler) {
Map<Object,Object> sessionInfoMap = redisTemplate.boundHashOps(id).entries();
if(sessionInfoMap != null && !sessionInfoMap.isEmpty()){
RedisDataSessionImpl redisDataSession = new RedisDataSessionImpl(sessionInfoMap);
resultHandler.handle(Future.succeededFuture