欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springmvc+mybatis+redis的session共享+maven管理

程序员文章站 2022-04-18 11:25:26
负载均衡搭建:http://www.cnblogs.com/guoyansi19900907/p/8717746.html redis安装:http://www.cnblogs.com/guoyansi19900907/p/8706856.html 文件格式: pom.xml jdbc.proper ......

负载均衡搭建:http://www.cnblogs.com/guoyansi19900907/p/8717746.html

redis安装:http://www.cnblogs.com/guoyansi19900907/p/8706856.html

文件格式:

springmvc+mybatis+redis的session共享+maven管理

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringMybatisRedisGroup</groupId>
    <artifactId>SpringMybatisRedisArtifact</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringMybatisRedisArtifact Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- spring版本-->
        <spring.version>4.3.10.RELEASE</spring.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.9</log4j.version>
    </properties>


    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.20</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
        </dependency>
        <!--springsession-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.3.2.RELEASE</version>
        </dependency>
        <!--redis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring-redis-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.0.RELEASE</version>
        </dependency>
        <!-- AOP相关包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- 日志相关包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>smr</finalName>
        <!--防止xml或properties打包被遗漏-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**.*</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springmvc-mybatis?zeroDateTimeBehavior=convertToNull&amp;allowMultiQueries=true&amp;useUnicode=true&amp;characterEncoding
jdbc.username=root
jdbc.password=gys
jdbc.initialSize=1
jdbc.maxActive=20
jdbc.minIdle=1
jdbc.maxIdle=5

redis.properties

redis.host=192.168.123.128
redis.port=6379
redis.password=123
redis.maxIdle=20
redis.maxTotal=500
redis.maxWaitMillis=1000
redis.testOnBorrow=true

log4j.properties

#USE THIS SETTING FOR OUTPUT MYBATIS`s SQL ON THE CONSOLE
log4j.rootLogger=INFO, Console

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p [%c] - %m%n

log4j.logger.com.lazy.smr=DEBUG

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--属性与字段开启驼峰命名规则对应-->
        <setting name="mapUnderscoreToCamelCase" value="false"/>
          <!-- 这个配置使全局的映射器启用或禁用缓存 -->
          <setting name="cacheEnabled" value="true"/>
          <!-- 允许jdbc支持生成的键.需要适合的驱动.如果设置为true,则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
          <setting name="useGeneratedKeys" value="false"/>
          <!--配置默认的执行器.simple执行器没有什么特别之处.reuse执行器重用预处理语句.batch执行器重用语句和批批量更新  -->
          <setting name="defaultExecutorType" value="REUSE"/>
          <!-- 全局启用或禁用延迟加载.当禁用时,所有关联对象都会即时加载 -->
          <setting name="lazyLoadingEnabled" value="true"/>
          <!-- 关闭层级加载 -->
          <setting name="aggressiveLazyLoading" value="false"/>
          <!--设置超时时间,它决定驱动等待一个数据库响应的时间  -->
          <setting name="defaultStatementTimeout" value="25000"/>
          <!-- 防止mybatis的log4j配置被忽略 -->
          <setting name="logImpl" value="LOG4J"/>
      </settings>
    
    <!--在此处为创建JavaBean的别名 -->

  <!--  <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="oracle"></property>
        </plugin>
    </plugins> -->
    <!-- 配置映射文件 -->
    <!-- <mappers>
        <mapper resource="orm/shyf/ShyfSqlMapper.xml"/>
    </mappers> -->
</configuration>

spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">


<!-- <context:annotation-config /> -->
<!-- 自动扫描的包-->
<context:component-scan base-package="com.lazy.smr.*" />


<!-- 加载数据库连接配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" system-properties-mode="FALLBACK"/>
    <!-- 加载数据库连接配置文件 -->
<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" />

<!-- 定义数据源Bean -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.driverClassName}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="minIdle" value="${jdbc.minIdle}" />
        <!--<property name="maxIdle" value="${jdbc.maxIdle}" />-->
    </bean>
    <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
        <!--秒-->
        <property name="maxInactiveIntervalInSeconds" value="60" />
    </bean>
    <!--redis数据源-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxTotal}" />
        <!--<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />-->
    </bean>
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <!--<property name="password" value="${redis.password}" />-->
        <property name="timeout" value="3000" />
        <property name="usePool" value="true" />
        <property name="poolConfig" ref="jedisPoolConfig" />
    </bean>

<!-- MyBatis的SqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="prototype">
        <!-- mapper文件配置 -->
        <property name="mapperLocations" value="classpath:com/lazy/smr/mapper/**" />
        <!-- 数据源 --> 
        <property name="dataSource" ref="dataSource" />
        <!-- mybatis的配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!--给mybatis配置扫描别名-->
        <!-- <property name="typeAliasesPackage" value="com.gys.sm.fun.**.bean.**" /> -->
    </bean>

<!-- sqlSessionTemplate -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!--事务管理  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 使用注解管理事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
    
    <!-- 采用自动扫描方式 创建 mapper bean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.teamsum.exports" />
        <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate" />
        <property name="annotationClass" value="org.springframework.stereotype.Repository" />
    </bean>
</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 <!--
         1.开启springmvc的注解模式
         2.简化配置:
             (1)自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
             (2)提供一系列:数据绑定,数字和日期的format  @NumberFormat,@dataTimeFormat,xml,json默认读写支持
      -->
<mvc:annotation-driven>
        <!-- @ResponseBody String时 使用utf-8 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
              <property name="supportedMediaTypes">
                  <list>
                      <value>text/plain;charset=UTF-8</value>
                      <value>text/html;charset=UTF-8</value>
                 </list>
              </property>
            </bean>
           </mvc:message-converters>
    </mvc:annotation-driven>
    
    <!-- 给service层添加事务处理增强 -->
    <context:component-scan base-package="com.lazy.smr">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>

<!-- 总拦截器 -->
    <!-- <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.gys.sm.item.interceptor.MyInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors> -->

<!-- 视图解析器 -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp" />
        <property name="suffix" value=".jsp" />
    </bean>
<!-- 对静态资源的访问 -->
<mvc:default-servlet-handler />

<!-- 上传配置 
        不配置会出现错误:net::ERR_CONNECTION_RESET 
    -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传的最大限制 -->
        <property name="maxUploadSize" value="209715200" />
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 上传文件的解析 -->
        <property name="resolveLazily" value="true" />
    </bean>
</beans>

IndexController.java

package com.lazy.smr.controller;

import com.alibaba.fastjson.JSON;
import com.lazy.smr.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @RequestMapping("index")
    public String page(){
        return "/index";
    }

    @RequestMapping("/login")
    public String login(HttpSession session) {
        User user=new User();
        user.setName("gys");
        user.setAge(2);
        session.setAttribute("user", JSON.toJSONString(user));
        return "/success";
    }

    @ResponseBody
    @RequestMapping("/get")
    public Object get(HttpSession session) {
        Object user=session.getAttribute("user");
        return user+"==========>22";
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">


    <!--springmv日志debug异常,javax.naming.NameNotFoundException start -->
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.default</param-name>
        <param-value>dev</param-value>
    </context-param>
    <context-param>
        <param-name>spring.liveBeansView.mbeanDomain</param-name>
        <param-value>dev</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>

    <!-- 启动Web容器时执行系统监听器,并且自动装配spring的相关配置信息 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 导入spring-mvc配置文件 start -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>