session自己定义存储。怎样更好地进行session共享;





读tomcat源代码,org.apache.catalina.session.FileStore可知





一、详见:

方法1 public void save(Session session)

try {

            ((StandardSession)session).writeObjectData(oos);

        } finally {

            oos.close();

        }

方法2 public Session load(String id)

    ois = new ObjectInputStream(bis);





    StandardSession session = (StandardSession) manager.createEmptySession();

    session.readObjectData(ois);

    session.setManager(manager);

return (session);

二、在conf/context.xml文件设置:这个是针对全部的项目了。也能够针对详细项目来配置在server.xml中。

打开context.xml,在<Context>节点下加入例如以下<Manager>节点:

<Manager className="org.apache.catalina.session.PersistentManager" >

    debug=0

    saveOnRestart="true"

    maxActiveSession="-1"

    minIdleSwap="-1"

    maxIdleSwap="-1"

    maxIdleBackup="-1"

    <Store className="org.apache.catalina.session.FileStore" directory="../session" />

//这里代表的是文件持久化.也能够自己实现Store

</Manager>

三、源代码见下文

 * Licensed to the Apache Software Foundation (ASF) under one or more









package org.apache.catalina.session;









import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.ArrayList;





import javax.servlet.ServletContext;





import org.apache.catalina.Container;

import org.apache.catalina.Context;

import org.apache.catalina.Loader;

import org.apache.catalina.Session;

import org.apache.catalina.util.CustomObjectInputStream;









/**

 * Concrete implementation of the <b>Store</b> interface that utilizes

 * a file per saved Session in a configured directory.  Sessions that are

 * saved are still subject to being expired based on inactivity.

 *

 * @author Craig R. McClanahan

 */

public final class FileStore extends StoreBase {









    // ----------------------------------------------------- Constants









    /**

     * The extension to use for serialized session filenames.

     */

    private static final String FILE_EXT = ".session";









    // ----------------------------------------------------- Instance Variables









    /**

     * The pathname of the directory in which Sessions are stored.

     * This may be an absolute pathname, or a relative path that is

     * resolved against the temporary work directory for this application.

     */

    private String directory = ".";









    /**

     * A File representing the directory in which Sessions are stored.

     */

    private File directoryFile = null;









    /**

     * The descriptive information about this implementation.

     */

    private static final String info = "FileStore/1.0";





    /**

     * Name to register for this Store, used for logging.

     */

    private static final String storeName = "fileStore";





    /**

     * Name to register for the background thread.

     */

    private static final String threadName = "FileStore";









    // ------------------------------------------------------------- Properties









    /**

     * Return the directory path for this Store.

     */

    public String getDirectory() {





        return (directory);





    }









    /**

     * Set the directory path for this Store.

     *

     * @param path The new directory path

     */

    public void setDirectory(String path) {





        String oldDirectory = this.directory;

        this.directory = path;

        this.directoryFile = null;

        support.firePropertyChange("directory", oldDirectory,

                                   this.directory);





    }









    /**

     * Return descriptive information about this Store implementation and

     * the corresponding version number, in the format

     * <code>&lt;description&gt;/&lt;version&gt;</code>.

     */

    @Override

    public String getInfo() {





        return (info);





    }





    /**

     * Return the thread name for this Store.

     */

    public String getThreadName() {

        return(threadName);

    }





    /**

     * Return the name for this Store, used for logging.

     */

    @Override

    public String getStoreName() {

        return(storeName);

    }









    /**

     * Return the number of Sessions present in this Store.

     *

     * @exception IOException if an input/output error occurs

     */

    @Override

    public int getSize() throws IOException {





        // Acquire the list of files in our storage directory

        File file = directory();

        if (file == null) {

            return (0);

        }

        String files[] = file.list();





        // Figure out which files are sessions

        int keycount = 0;

        for (int i = 0; i < files.length; i++) {

            if (files[i].endsWith(FILE_EXT)) {

                keycount++;

            }

        }

        return (keycount);





    }









    // --------------------------------------------------------- Public Methods









    /**

     * Remove all of the Sessions in this Store.

     *

     * @exception IOException if an input/output error occurs

     */

    @Override

    public void clear()

        throws IOException {





        String[] keys = keys();

        for (int i = 0; i < keys.length; i++) {

            remove(keys[i]);

        }





    }









    /**

     * Return an array containing the session identifiers of all Sessions

     * currently saved in this Store.  If there are no such Sessions, a

     * zero-length array is returned.

     *

     * @exception IOException if an input/output error occurred

     */

    @Override

    public String[] keys() throws IOException {





        // Acquire the list of files in our storage directory

        File file = directory();

        if (file == null) {

            return (new String[0]);

        }





        String files[] = file.list();

        

        // Bugzilla 32130

        if((files == null) || (files.length < 1)) {

            return (new String[0]);

        }





        // Build and return the list of session identifiers

        ArrayList<String> list = new ArrayList<String>();

        int n = FILE_EXT.length();

        for (int i = 0; i < files.length; i++) {

            if (files[i].endsWith(FILE_EXT)) {

                list.add(files[i].substring(0, files[i].length() - n));

            }

        }

        return list.toArray(new String[list.size()]);





    }









    /**

     * Load and return the Session associated with the specified session

     * identifier from this Store, without removing it.  If there is no

     * such stored Session, return <code>null</code>.

     *

     * @param id Session identifier of the session to load

     *

     * @exception ClassNotFoundException if a deserialization error occurs

     * @exception IOException if an input/output error occurs

     */

    @Override

    public Session load(String id)

        throws ClassNotFoundException, IOException {





        // Open an input stream to the specified pathname, if any

        File file = file(id);

        if (file == null) {

            return (null);

        }





        if (! file.exists()) {

            return (null);

        }

        if (manager.getContainer().getLogger().isDebugEnabled()) {

            manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".loading",

                             id, file.getAbsolutePath()));

        }





        FileInputStream fis = null;

        BufferedInputStream bis = null;

        ObjectInputStream ois = null;

        Loader loader = null;

        ClassLoader classLoader = null;

        ClassLoader oldThreadContextCL = Thread.currentThread().getContextClassLoader();

        try {

            fis = new FileInputStream(file.getAbsolutePath());

            bis = new BufferedInputStream(fis);

            Container container = manager.getContainer();

            if (container != null)

                loader = container.getLoader();

            if (loader != null)

                classLoader = loader.getClassLoader();

            if (classLoader != null) {

                Thread.currentThread().setContextClassLoader(classLoader);

                ois = new CustomObjectInputStream(bis, classLoader);

            } else {

                ois = new ObjectInputStream(bis);

            }





            StandardSession session =

                    (StandardSession) manager.createEmptySession();

            session.readObjectData(ois);

            session.setManager(manager);

            return (session);

        } catch (FileNotFoundException e) {

            if (manager.getContainer().getLogger().isDebugEnabled())

                manager.getContainer().getLogger().debug("No persisted data file found");

            return (null);

        } catch (IOException e) {

            if (bis != null) {

                try {

                    bis.close();

                } catch (IOException f) {

                    // Ignore

                }

            }

            if (fis != null) {

                try {

                    fis.close();

                } catch (IOException f) {

                    // Ignore

                }

            }

            throw e;

        } finally {

            if (ois != null) {

                // Close the input stream

                try {

                    ois.close();

                } catch (IOException f) {

                    // Ignore

                }

            }

            Thread.currentThread().setContextClassLoader(oldThreadContextCL);

        }

    }









    /**

     * Remove the Session with the specified session identifier from

     * this Store, if present.  If no such Session is present, this method

     * takes no action.

     *

     * @param id Session identifier of the Session to be removed

     *

     * @exception IOException if an input/output error occurs

     */

    @Override

    public void remove(String id) throws IOException {





        File file = file(id);

        if (file == null) {

            return;

        }

        if (manager.getContainer().getLogger().isDebugEnabled()) {

            manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".removing",

                             id, file.getAbsolutePath()));

        }

        file.delete();





    }









    /**

     * Save the specified Session into this Store.  Any previously saved

     * information for the associated session identifier is replaced.

     *

     * @param session Session to be saved

     *

     * @exception IOException if an input/output error occurs

     */

    @Override

    public void save(Session session) throws IOException {





        // Open an output stream to the specified pathname, if any

        File file = file(session.getIdInternal());

        if (file == null) {

            return;

        }

        if (manager.getContainer().getLogger().isDebugEnabled()) {

            manager.getContainer().getLogger().debug(sm.getString(getStoreName()+".saving",

                             session.getIdInternal(), file.getAbsolutePath()));

        }

        FileOutputStream fos = null;

        ObjectOutputStream oos = null;

        try {

            fos = new FileOutputStream(file.getAbsolutePath());

            oos = new ObjectOutputStream(new BufferedOutputStream(fos));

        } catch (IOException e) {

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException f) {

                    // Ignore

                }

            }

            throw e;

        }





        try {

            ((StandardSession)session).writeObjectData(oos);

        } finally {

            oos.close();

        }





    }









    // -------------------------------------------------------- Private Methods









    /**

     * Return a File object representing the pathname to our

     * session persistence directory, if any.  The directory will be

     * created if it does not already exist.

     */

    private File directory() throws IOException {





        if (this.directory == null) {

            return (null);

        }

        if (this.directoryFile != null) {

            // NOTE:  Race condition is harmless, so do not synchronize

            return (this.directoryFile);

        }

        File file = new File(this.directory);

        if (!file.isAbsolute()) {

            Container container = manager.getContainer();

            if (container instanceof Context) {

                ServletContext servletContext =

                    ((Context) container).getServletContext();

                File work = (File)

                    servletContext.getAttribute(ServletContext.TEMPDIR);

                file = new File(work, this.directory);

            } else {

                throw new IllegalArgumentException

                    ("Parent Container is not a Context");

            }

        }

        if (!file.exists() || !file.isDirectory()) {

            if (!file.delete() && file.exists()) {

                throw new IOException(

                        sm.getString("fileStore.deleteFailed", file));

            }

            if (!file.mkdirs() && !file.isDirectory()) {

                throw new IOException(

                        sm.getString("fileStore.createFailed", file));

            }

        }

        this.directoryFile = file;

        return (file);





    }









    /**

     * Return a File object representing the pathname to our

     * session persistence file, if any.

     *

     * @param id The ID of the Session to be retrieved. This is

     *    used in the file naming.

     */

    private File file(String id) throws IOException {





        if (this.directory == null) {

            return (null);

        }

        String filename = id + FILE_EXT;

        File file = new File(directory(), filename);

        return (file);





    }









}

session自己定义存储,怎样更好地进行session共享;读tomcat7源代码,org.apache.catalina.session.FileStore可知的更多相关文章

  1. org.apache.catalina.session.StandardManager doLoad

    转载自:http://www.cnblogs.com/java727/p/3300613.html SEVERE: IOException while loading persisted sessio ...

  2. PHP SESSION机制,从存储到读取

    PHP中,如果要获取SESSION数据,必须要有对应的session_id,session_id的获取方式有两种 1.基于客户端的cookie 2.基于url 先说第一种情况,基于客户端的cookie ...

  3. tomcat启动报错 ERROR o.a.catalina.session.StandardManager 182 - Exception loading sessions from persiste

    系统:centos6.5 x86_64 jdk: 1.8.0_102 tomcat:8.0.37 tomcat 启动报错: ERROR o.a.catalina.session.StandardMan ...

  4. org.apache.shiro.session.InvalidSessionException: java.lang.IllegalStateException: getAttribute: Session already invalidated] with root cause

    1.遇到以下异常,找了好长时间,终于解决,报的异常如下: 七月 07, 2017 3:02:16 下午 org.apache.catalina.core.StandardWrapperValve in ...

  5. PHP临时文件session的分级存储与定期删除

    在Windows上PHP默认的Session服务端文件存放在C:\WINDOWS\Temp下,如果说并发访问很大或者 session建立太多,目录下就会存在大量类似sess_xxxxxx的sessio ...

  6. php之memcached存储session配置、存储、获取

    [session] ①.session.save_handler = memcache session.save_handler 定义了来存储和获取与会话关联的数据的处理器的名字,默认是files ② ...

  7. .net的session详解 存储模式 存到数据库中 使用范围与大小限制 生命周期

    Session又称为会话状态,是Web系统中最常用的状态,用于维护和当前浏览器实例相关的一些信息.举个例子来说,我们可以把已登录用户的用户名放在Session中,这样就能通过判断Session中的某个 ...

  8. PPT | Docker定义存储-让应用无痛运行

    编者注: 本文为9月27日晚上8点有容云平台存储架构师张朝潞在腾讯课堂中演讲的PPT,本次课堂为有容云主办的线上直播Docker Live时代●Online Meetup-第三期:Docker定义存储 ...

  9. 网络:Session原理及存储

    一.Session的工作流程 二.会话保持 会话保持是负载均衡最常见的问题之一,会话保持是指在负载均衡器上实现的一种机制,可以识别客户端与服务器之间交互过程的关连性,在作负载均衡的同时还保证一系列相关 ...

随机推荐

  1. 剑指Offer 二进制中一的个数

    链接:https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8 来源:牛客网 public class So ...

  2. ubuntu 为firefox 安装flash_player

    1.下载安装包install_flash_player_11_linux.i386.tar.gz: 2.解压文件:$ tar -xvf install_flash_player_11_linux.i3 ...

  3. C语言集锦(二) 图像显示 Windows和Linux

    关于图像显示有很多库可以用,Windows下有GDI,GDI+,D3D等,Linux下有X Window和Wayland,此外还有OpenGL ,SDL等图形库以及各种GUI库. 了解最原始的方式,对 ...

  4. 如何循序渐进向.NET架构师发展

    微软的DotNet开发绝对是属于那种入门容易提高难的技术.而要能够成为DotNet架构师没有三年或更长时间的编码积累基本上是不可能的.特别是在大型软件项目中,架构师是项目核心成员,承上启下,因此RUP ...

  5. HDU 3068 Manacher

    题目链接:http://hdu.hustoj.com/showproblem.php?pid=3068 今天学习一下马拉车算法,虽然mg讲过,但是没有系统去学. 算法学习:参考博客 马拉车模板题. # ...

  6. React-Native解决ListView 在Android手机上无吸顶效果

    stickySectionHeadersEnabled={true} stickyHeaderIndices={[0]}

  7. 洛谷——P1657 选书

    P1657 选书 题目描述 学校放寒假时,信息学奥赛辅导老师有1,2,3……x本书,要分给参加培训的x个人,每人只能选一本书,但是每人有两本喜欢的书.老师事先让每个人将自己喜欢的书填写在一张表上.然后 ...

  8. javascript 对象初探 (四)--- 内建对象之旅之Boolean

    var a = new Boolean() 我们要明白一点在这里的b是一个对象而不是一个基本数据类型的布尔值.如果想将b转化成基本数据类型的布尔值,我们可以调用她的valueof()方法(继承自Obj ...

  9. Android入门:MVC模式(中)

    MVC 模式的最基本概念是分层设计,把我们的代码基于 View(视图).Model(模型).Controller(控制器)进行分类封装,这样做的目的是为了清晰结构,使代码更易维护和扩展. 在上一篇文章 ...

  10. 线程安全-一个VC下多个网络请求

    一.线程安全变量控制显示隐藏loading框 问题描写叙述: 同一页面有两个异步网络请求,第一个请求開始,loading旋转.第二个请求開始loading旋转.第一个结束,loading停止旋转,但是 ...