spring boot 实现自定义sessionid并保存Redis

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

实现ExpiringSession接口

package com.uwo.oss.session.configuration;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.session.ExpiringSession;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
 * session
 * @author hao.yan
 */
public final class TokenSession implements ExpiringSession, Serializable{

    private final Logger log = LoggerFactory.getLogger(TokenSession.class);
    // session id
    private String id;
    // 属性
    private Map attributes;
    // 创建时间
    private long creationTime;
    // 上一次操作时间
    private long lastAccessedTime;
    // 过期时间
    private int maxInactiveInterval;

    public TokenSession(){
        this("UWO-" + UUID.randomUUID().toString());
    }

    public TokenSession(String id) {
        this.id = id;
        this.attributes = new HashMap();
        this.creationTime = System.currentTimeMillis();
        this.lastAccessedTime = this.creationTime;
        this.maxInactiveInterval = 1800;
    }

    public TokenSession(ExpiringSession session) {
        if (session == null)
            throw new IllegalArgumentException("session cannot be null");
        this.id = session.getId();
        this.attributes = new HashMap(session.getAttributeNames().size());
        for (String attrName : session.getAttributeNames()) {
            Object attrValue = session.getAttribute(attrName);
            this.attributes.put(attrName, attrValue);
        }
        this.lastAccessedTime = session.getLastAccessedTime();
        this.creationTime = session.getCreationTime();
        this.maxInactiveInterval = session.getMaxInactiveIntervalInSeconds();
    }

    @Override
    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public long getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(long creationTime) {
        this.creationTime = creationTime;
    }

    public long getLastAccessedTime() {
        return lastAccessedTime;
    }

    public void setLastAccessedTime(long lastAccessedTime) {
        this.lastAccessedTime = lastAccessedTime;
    }

    public void setMaxInactiveIntervalInSeconds(int interval) {
        this.maxInactiveInterval = interval;
    }

    @JsonIgnore
    public int getMaxInactiveIntervalInSeconds() {
        return this.maxInactiveInterval;
    }

    public Map getAttributes() {
        return attributes;
    }

    @JsonIgnore
    @Override
    public Set getAttributeNames() {
        return this.attributes.keySet();
    }

    @Override
    public  T getAttribute(String attributeName) {
        return (T)attributes.get(attributeName);
    }

    @Override
    public void removeAttribute(String attributeName) {
        this.attributes.remove(attributeName);
    }

    @Override
    public void setAttribute(String attributeName, Object attributeValue) {
        if (attributeValue == null) {
            removeAttribute(attributeName);
        }
        else {
            this.attributes.put(attributeName, attributeValue);
        }
    }

    public boolean isExpired() {
        return isExpired(System.currentTimeMillis());
    }

    private boolean isExpired(long now) {
        if (this.maxInactiveInterval < 0) 
            return false;
        return now - TimeUnit.SECONDS
                .toMillis(this.maxInactiveInterval) >= this.lastAccessedTime;
    }

}

实现SessionRepository接口

package com.uwo.oss.session.configuration;
import com.uwo.oss.common.kits.JsonKits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.SessionRepository;
import java.util.concurrent.TimeUnit;
/**
 * session 存储器
 * @author hao.yan
 */
public class UwoSessionRepository implements SessionRepository{

    private final Logger log = LoggerFactory.getLogger(RedisOperationsSessionRepository.class);

    private SessionProperties sessionProperties;

    private RedisTemplate redisTemplate;

    public UwoSessionRepository(RedisTemplate redisTemplate, SessionProperties sessionProperties){
        this.redisTemplate = redisTemplate;
        this.sessionProperties = sessionProperties;
    }

    /**
     * 创建session
     * @return
     */
    @Override
    public TokenSession createSession() {
        TokenSession  session = new TokenSession();
        session.setMaxInactiveIntervalInSeconds(sessionProperties.getMaxInactiveIntervalInSeconds());
        if (log.isDebugEnabled())
            log.debug("create session: value = " + JsonKits.object2Json(session));
        return session;
    }

    /**
     * 通过session id获取session
     * @param id
     * @return
     */
    @Override
    public TokenSession getSession(String id) {
        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(id);
        Object o = boundValueOperations.get();
        if(o == null)
            return null;

        if (log.isDebugEnabled())
            log.debug("find session : value = " + o.toString());

        // 格式转换
        TokenSession session = JsonKits.json2Object(o.toString(), TokenSession.class);
        if(session == null)
            return null;
        // 判断是否过期
        if(session.isExpired())
            return null;
        session.setLastAccessedTime(System.currentTimeMillis());
        return session;
    }

    /**
     * 保存session
     * @param session
     */
    @Override
    public void save(TokenSession session) {
        if(session == null)
            return;

        // 格式转换
        String json = JsonKits.object2Json(session);
        if(json == null)
            return;

        if (log.isDebugEnabled())
            log.debug("save session : value = " + json);

        // 保存session设置过期时间
        redisTemplate.boundValueOps(session.getId()).set(json, sessionProperties.getMaxInactiveIntervalInSeconds(), TimeUnit.SECONDS);
    }

    /**
     * 删除session
     * @param id
     */
    @Override
    public void delete(String id) {
        // 查看session 判断是否存在
        TokenSession session = getSession(id);
        if (session == null)
            return;

        if (log.isDebugEnabled())
            log.debug("delete session : id = " + id);
        // 删除session
        redisTemplate.delete(id);
    }

}

写configuration配置类

package com.uwo.oss.session.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration;
import org.springframework.util.StringValueResolver;
import java.util.Map;
/**
 * session 配置类
 * @author hao.yan
 */
@Order(1)
@Configuration
@EnableScheduling
@EnableConfigurationProperties({SessionProperties.class})
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration {

    private final Logger log = LoggerFactory.getLogger(RedisHttpSessionConfiguration.class);

    @Autowired
    private SessionProperties sessionProperties;

    // 失效时间
    private Integer maxInactiveIntervalInSeconds = 1800;

    @Bean
    public RedisOperationsSessionRepository sessionRepository(
            @Autowired RedisTemplate redisTemplate) {
        log.warn("session repository =============");
        RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
                redisTemplate, sessionProperties);
        return sessionRepository;
    }
}

转载于:https://my.oschina.net/yan5845hao/blog/1549022

你可能感兴趣的:(spring boot 实现自定义sessionid并保存Redis)