1. 程式人生 > >Tomcat生成的session持久化到MySQL

Tomcat生成的session持久化到MySQL

-m tst roc resp utf8 無效 ever pro contains

Telling Tomcat to save session records in MySQL

此部分內容摘自 MySQL cookbook 3th。具體內容不做翻譯,哈哈,懶

The default Tomcat default session storage mechanism uses temporary files. To save
sessions using JDBC with MySQL instead, follow this procedure:

  1. Create a table to hold session records.
  2. Make sure that Tomcat can access the proper JDBC driver.
  3. Modify the appropriate Tomcat configuration file to specify use of a persistent ses‐
    sion manager for the relevant application context.

None of these steps involve modifying the sample session script in any way, which
reflects how Tomcat implements session support above the application level.

Create the Tomcat session table.

  1. Tomcat stores several types of information in the session table:
  2. The session ID. By default, IDs are 32-character MD5 values.
  3. The application name.
  4. The session data. This is a serialized string.
  5. Whether the session is valid, as a single byte.
  6. The maximum permitted inactivity time, as a 32-bit integer measured in seconds.
  7. The last access time, as a 64-bit integer.

The following table satisfies those specifications; create it now before proceeding:

CREATE TABLE tomcat_session
(
    id VARCHAR(32) NOT NULL,
    app VARCHAR(255),
    data LONGBLOB,
    valid_session CHAR(1) NOT NULL,
    max_inactive INT NOT NULL,
    update_time BIGINT NOT NULL,
    PRIMARY KEY (id),
    INDEX (app)
);

Place the JDBC driver where Tomcat can find it.

Because Tomcat itself manages sessions, it must be able to access the JDBC driver
used to store sessions in a database. It’s common to install drivers in the lib directory
of the Tomcat tree so that they’re available both to Tomcat and to applications.(備註:如果war中中已經有引用 mysql jdbc driver 則不需要專門將驅動jar包拷貝到 tomcat 的lib 目錄下)

Modify the Tomcat configuration file.

To tell Tomcat to use the tomcat_session table, modify the mcb application context
file. Change location into the webapps/mcb/META-INF under the Tomcat we
bapps directory, copy context.xml.jdbc to context.xml, and restart Tomcat.
If you look in context.xml, you’ll find a <Context> element containing a <Manager> element that specifies the use of JDBC for MySQL-based session storage:

<Manager
className="org.apache.catalina.session.PersistentManager"
    saveOnRestart="true"
    maxIdleBackup="600"
    maxIdleSwap="1200"
    minIdleSwap="900">
<Store
    className="org.apache.catalina.session.JDBCStore"
    driverName="com.mysql.jdbc.Driver"
    connectionURL=
    "jdbc:mysql://localhost/cookbook?user=cbuser&amp;password=cbpass&amp;useSSL=false"
    sessionTable="tomcat_session"
    sessionIdCol="id"
    sessionAppCol="app"
    sessionDataCol="data"
    sessionValidCol="valid_session"
    sessionMaxInactiveCol="max_inactive"
    sessionLastAccessedCol="update_time"
/>
</Manager>

The <Manager> element attributes specify general session-related options. Within the
<Manager> element body, the <Store> element provides attributes pertaining to the
JDBC driver. The following discussion focuses on the attributes shown in the example,
but there are others you can use. For more information, see the Tomcat session-
management documentation.

The <Manager> attributes shown in the example have the following meanings:

  • className:The Java class that implements persistent session storage. It must be
    org.apache.catalina.session.PersistentManager .
  • saveOnRestart:Whether application sessions survive server restarts. Set it to true to have Tomcat
    save current sessions when it shuts down (and reload them when it starts up).
  • maxIdleBackup:The number of seconds before inactive sessions are eligible for being saved to MySQL. A value of -1 (the default) means “never.”
  • maxIdleSwap:The number of seconds before idle sessions should be swapped (saved to MySQL and passivated out of server memory). A value of -1 (the default) means “never.”
    If not -1 , the value should be at least as great as maxIdleBackup .
  • minIdleSwap:The number of seconds before idle sessions are eligible to be swapped. A value of -1 (the default) means “never.” If not -1 , the value should be less than maxIdleSwap

Within the <Manager> element, the <Store> element indicates how to connect to the
database server, the names of the database and table for storing session records, and the
names of the columns in the table:

  • className:The name of a class that implements the org.apache.catalina.Store interface.
    For JDBC-based storage managers, the value is org.apache.catalina.session.JDBCStore .

  • driverName:The class name for the JDBC driver. For the Connector/J driver, the value is com.mysql.jdbc.Driver.

  • connectionURL:The URL for connecting to the database server, with characters that are special in XML properly encoded. The following URL connects to the MySQL server on the local host, using a database, username, and password of cookbook , cbuser , and cbpass , respectively. Notice that the & character that separates the user and pass word connection parameters is written as the & entity: jdbc:mysql://localhost/cookbook?user=cbuser&password=cbpass
  • sessionTable The table in which to store session records. For our example, this is the tomcat_session table described earlier.

(The database that contains the table appears in the connectionURL value.) The remaining

可能存在的問題

MySQL 大版本指尖引用類名包路徑改變

此部分內容摘自:com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區別 serverTimezone設定

com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的

1、JDBC連接Mysql5 com.mysql.jdbc.Driver:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=1234

2、JDBC連接Mysql6 com.mysql.cj.jdbc.Driver, 需要指定時區serverTimezone:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=1234

在設定時區的時候,如果設定serverTimezone=UTC,會比中國時間早8個小時,如果在中國,可以選擇Asia/Shanghai或者Asia/Hongkong,例如:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?serverTimezone=Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=

Java連接MySQL數據庫,提示Establishing SSL connection without警告

此內容摘自:Java連接MySQL數據庫,提示Establishing SSL connection without警告

Java在連接MySQL數據庫時,輸出如下警告信息**

Tue Jul 11 18:04:07 CST 2017 WARN: Establishing SSL connection without server‘s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn‘t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false‘. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

解決辦法

  1. 在jdbc連接後添加 useSSL=false 參數
url=jdbc:mysql://localhost:3306/es?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
  1. 如果以上辦法無效,則降低 mysql-connector-java 依賴版本,如下
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

總結

一般來說小版本之間的跨度不影響使用,但是大版本之間的使用差別將會很大,所以得要確認MySQL的版本並找到對應最合適的驅動。

tomcat 默認是將這部分session相關的信息放在文件裏邊的,通過上述的配置能夠將對應的信息放到MySQL中,如果大並發大數據量的情況下性能應該更好一些。實際上如果有多個tomcat,可以讓這些Tomcat都連接到該數據庫,則可以實現分布式session的共享。當然在大並發大數據的情況下往往更好的做法是將session的信息放到redis 中,性能應該會更好一些。

歡迎轉載,但請註明本文鏈接,謝謝你。

2018.8.19 17:57

Tomcat生成的session持久化到MySQL