• 搭建eclipse版的ssm+maven+tk.mybatis+redis及mybatis+spring多数据源配置集成的demo


    前言:我这里搭建好eclipse版的ssm+maven+tk.mybatis+redis及mybatis+spring多数据源配置集成的demo。新手快速上手直接看demo。

    最后处提供完整高质量demo!!!

     

    准备工作

    1、redis下载及配置(demo中有)

    (1)下载window或linux版(那本地需要装虚拟机)redis

    (2)redis.conf修改(linux版也一样)

      注释:# bind 127.0.0.1

      密码:requirepass 123(自定义密码)

    (3)运行,双击redis-startup.bat运行

    redis-startup.bat是我自己写的脚本,内容很简单

    redis-server.exe redis.conf

    2、Eclipse配置mybatis-generator插件

    参考:https://blog.csdn.net/u012825737/article/details/79117540

    配置好后,右键generatorConfiguration.xml即可生成文件

    先来一波完整的配置

    3、框架搭建的配置文件

    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/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>com.gx</groupId>
    	<artifactId>more-datasource</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>war</packaging>
    
    	<!-- maven配置 -->
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.5.1</version>
    				<configuration>
    					<source>1.8</source>
    					<target>1.8</target>
    					<encoding>utf-8</encoding>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    	
    	<!-- 版本配置 -->
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<!-- jar版本号 -->
    		<spring.version>4.3.14.RELEASE</spring.version> <!-- Spring版本号 -->
    		<freemarker.version>2.3.23</freemarker.version>
    		<aopalliance.version>1.0</aopalliance.version> <!-- aopalliance版本号 -->
    		<aspectjweaver.version>1.8.10</aspectjweaver.version> <!-- aspectjweaver版本号 -->
    		<mybatis.version>3.4.1</mybatis.version> <!-- mybatis版本号 -->
    		<tk.mybatis.mapper.version>3.3.9</tk.mybatis.mapper.version> <!-- tk.mybatis.mapper版本号 -->
    		<mybatis-spring.version>1.3.1</mybatis-spring.version>
    		<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
    		<druid.version>1.1.10</druid.version> <!-- druid版本号 -->
    		<jackson-databind.version>2.9.5</jackson-databind.version>
    		<servlet-api.version>2.5</servlet-api.version>
    		<jsp-api.version>2.2</jsp-api.version>
    		<jstl.version>1.2</jstl.version>
    		<taglibs.standard.version>1.1.2</taglibs.standard.version>
    		<commons-fileupload.version>1.3.1</commons-fileupload.version>
    		<slf4j-log4j12.version>1.7.25</slf4j-log4j12.version>
    		<poi-ooxml.version>3.15-beta2</poi-ooxml.version>
    		<shiro.version>1.3.2</shiro.version>
    		<junit.version>4.12</junit.version>
    		<guava.version>26.0-jre</guava.version> <!-- guava工具集 -->
    		<spring-data-redis.vaersion>1.7.0.RELEASE</spring-data-redis.vaersion> <!-- redis -->
    		<jedis.vaersion>2.8.0</jedis.vaersion> <!-- redis -->
    		<commons-pool2.vaersion>2.4.2</commons-pool2.vaersion> <!-- redis -->
    	</properties>
    
    	<dependencies>
    		<!-- 测试包 -->
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>${junit.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-test</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<!--spring-mvc依赖 -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<!--事务管理依赖 -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-jdbc</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<!--使用aop方式管理和控制事务 -->
    		<dependency>
    			<groupId>aopalliance</groupId>
    			<artifactId>aopalliance</artifactId>
    			<version>${aopalliance.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.aspectj</groupId>
    			<artifactId>aspectjweaver</artifactId>
    			<version>${aspectjweaver.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context-support</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.freemarker</groupId>
    			<artifactId>freemarker</artifactId>
    			<version>${freemarker.version}</version>
    		</dependency>
    
    		<!--mybatis -->
    		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis</artifactId>
    			<version>${mybatis.version}</version>
    		</dependency>
    
    		<!--mybatis通用mapper -->
    		<dependency>
    			<groupId>tk.mybatis</groupId>
    			<artifactId>mapper</artifactId>
    			<version>${tk.mybatis.mapper.version}</version>
    		</dependency>
    
    		<!--spring-mybatis[把mybatis的mapper接口生成代理实现类交给spring容器统一管理] -->
    		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis-spring</artifactId>
    			<version>${mybatis-spring.version}</version>
    		</dependency>
    
    		<!--数据库连接驱动和数据库连接池druid -->
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>${mysql-connector-java.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>druid</artifactId>
    			<version>${druid.version}</version>
    		</dependency>
    
    		<!--json -->
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-databind</artifactId>
    			<version>${jackson-databind.version}</version>
    		</dependency>
    
    		<!--web -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>servlet-api</artifactId>
    			<version>${servlet-api.version}</version>
    			<scope>provided</scope>
    		</dependency>
    
    		<dependency>
    			<groupId>javax.servlet.jsp</groupId>
    			<artifactId>jsp-api</artifactId>
    			<version>${jsp-api.version}</version>
    			<scope>provided</scope>
    		</dependency>
    
    		<!-- jsp中使用jstl标签 -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>jstl</artifactId>
    			<version>${jstl.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>taglibs</groupId>
    			<artifactId>standard</artifactId>
    			<version>${taglibs.standard.version}</version>
    		</dependency>
    
    		<!-- springmvc 上传文件依赖 -->
    		<dependency>
    			<groupId>commons-fileupload</groupId>
    			<artifactId>commons-fileupload</artifactId>
    			<version>${commons-fileupload.version}</version>
    		</dependency>
    
    		<!-- slf4j日志包 -->
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j12</artifactId>
    			<version>${slf4j-log4j12.version}</version>
    		</dependency>
    
    		<!-- poi-ooxml自动引入操作xlsx文件所用到的其他包 -->
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>${poi-ooxml.version}</version>
    		</dependency>
    
    		<!-- shiro安全验证框架 -->
    		<dependency>
    			<groupId>org.apache.shiro</groupId>
    			<artifactId>shiro-spring</artifactId>
    			<version>${shiro.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.shiro</groupId>
    			<artifactId>shiro-ehcache</artifactId>
    			<version>${shiro.version}</version>
    		</dependency>
    
    		<!-- guava工具集 -->
    		<dependency>
    			<groupId>com.google.guava</groupId>
    			<artifactId>guava</artifactId>
    			<version>${guava.version}</version>
    		</dependency>
    
    		<!-- redis -->
    		<dependency>
    			<groupId>org.springframework.data</groupId>
    			<artifactId>spring-data-redis</artifactId>
    			<version>${spring-data-redis.vaersion}</version>
    		</dependency>
    		<dependency>
    			<groupId>redis.clients</groupId>
    			<artifactId>jedis</artifactId>
    			<version>${jedis.vaersion}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.commons</groupId>
    			<artifactId>commons-pool2</artifactId>
    			<version>${commons-pool2.vaersion}</version>
    		</dependency>
    
    	</dependencies>
    
    </project>

    generatorConfiguration.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
      PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
      "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <!-- 配置生成器 -->
    <generatorConfiguration>
        <!-- 引入配置文件 -->
        <properties resource="mybatisGeneratorinit.properties"/>
        <!-- 一个数据库一个context -->
        <!--defaultModelType="flat" 大数据字段,不分表 -->
        <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
            <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
            一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
            <property name="autoDelimitKeywords" value="true" />
            <!-- 生成的Java文件的编码 -->
            <property name="javaFileEncoding" value="utf-8" />
            <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
            <property name="beginningDelimiter" value="`" />
            <property name="endingDelimiter" value="`" />
            
            <!-- 格式化java代码 -->
            <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
            <!-- 格式化XML代码 -->
            <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
            <!-- 添加序列化 -->
            <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
            <!-- 添加toString方法 -->
            <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
            <!-- 通用mapper插件 -->
            <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
                <property name="mappers" value="${mapper.Mapper}"/><!-- Mapper继承接口 -->
            </plugin>
            
            <!-- 注释 -->
            <commentGenerator >
                <property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->
                <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->
            </commentGenerator>
            
            <!-- jdbc连接 -->
            <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
            <!-- 类型转换 -->
            <javaTypeResolver>
                <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
            
            <!-- 生成实体类地址 -->
            <javaModelGenerator targetPackage="${mapper.entityPackage}" targetProject="${project}" >
            	<property name="constructorBased" value="true" />
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
                <property name="rootClass" value="${mapper.entity}" /><!-- 继承entity -->
            </javaModelGenerator>
            <!-- 生成mapper.xml文件 -->
            <sqlMapGenerator targetPackage="${mapper.xmlPackage}" targetProject="${project}" >
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
            <!-- 生成mapper.xml对应client,也就是接口mapper -->
            <javaClientGenerator targetPackage="${mapper.mapperPackage}" targetProject="${project}" type="XMLMAPPER" >
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
            
            <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
            <table tableName="tb_book" domainObjectName="Book">
                <!-- 数据库表主键 -->
                <generatedKey column="book_id" sqlStatement="Mysql" identity="true" />
                <columnOverride column="book_price" javaType="java.lang.Double"></columnOverride>
            </table>
        </context>
    </generatorConfiguration>
    

    mybatisGeneratorinit.properties

    # Mybatis Generator configuration
    # 数据库连接配置
    jdbc_driver=com.mysql.jdbc.Driver
    jdbc_url=jdbc:mysql://localhost:3306/testdb_master?useSSL=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
    jdbc_user=root
    jdbc_password=root
    # 项目根路径
    project=more-datasource/src/main/java
    # 生成实体类位置
    mapper.entityPackage=com.gx.entity
    # 生成实体类继承的类
    mapper.entity=com.gx.common.base.entity.BaseEntity
    # 生成接口mapper位置
    mapper.mapperPackage=com.gx.mapper
    # 指定生成的Mapper文件继承的接口
    mapper.Mapper=com.gx.common.base.mapper.BaseMapper
    # mapper-xml文件的位置
    mapper.xmlPackage=com.gx.mapper.xml

    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">
        
        <!--扫描以下的实例交给springMvc容器管理-->
        <context:component-scan base-package="com.gx.controller"/>
        
        <!--开启mvc所有注解配置-->
        <mvc:annotation-driven />
      
        <!--配置jsp视图解析器-->
        <bean id="viewResoler" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
      
    </beans>

    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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <!--把tk.mybatis中mapper接口生成的代理对象交给spring容器管理-->
      <bean id="mapperScanner" class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描需要生成代理对象所有接口的包路径-->
        <property name="basePackage" value="com.gx.mapper"/>
      </bean>
      
      <!--把mybatis整合到spring容器管理-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--使用数据源dataSource-->
        <property name="dataSource" ref="dataSource"/>
        <!--把mybatis所有mapper映射配置文件整合到sqlSessionFactory对象中-->
        <property name="mapperLocations" value="classpath:com/gx/mapper/xml/*Mapper.xml"/>
        <!--mybatis配置-->
        <property name="configLocation" value="classpath:mybatis/mybatis.cofig.xml" />
        <!--插件配置-->
        <!--<property name="plugins">
          <props>
            <prop key=""/>
          </props>
        </property>-->
      </bean>
      
    </beans>

    spring-service.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"
           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">
      
        <!--扫描以下的交给spring容器管理-->
        <context:component-scan base-package="com.gx.common.datasource,com.gx.common.util,com.gx.service"/>
      
    </beans>

    spring-tx.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    	<!--配置事务管理器 -->
    	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    
    	<!--配置事务传播性 -->
    	<tx:advice id="txAdvice" transaction-manager="transactionManager">
    		<tx:attributes>
    			<!--service命名规范 -->
    			<tx:method name="add*" propagation="REQUIRED" />
    			<tx:method name="save*" propagation="REQUIRED" />
    			<tx:method name="insert*" propagation="REQUIRED" />
    			<tx:method name="delete*" propagation="REQUIRED" />
    			<tx:method name="remove*" propagation="REQUIRED" />
    			<tx:method name="update*" propagation="REQUIRED" />
    			<tx:method name="modify*" propagation="REQUIRED" />
    			<tx:method name="get*" propagation="SUPPORTS" />
    			<tx:method name="find*" propagation="SUPPORTS" />
    			<tx:method name="list*" propagation="SUPPORTS" />
    			<tx:method name="*" read-only="true" propagation="SUPPORTS" 
    			rollback-for="com.gx.common.base.exception.BaseBusinessException" />
    		</tx:attributes>
    	</tx:advice>
    
    	<!--组装事务传播和切入点 -->
    	<aop:config>
    		<!--impl包下的所有类所有方法 -->
    		<aop:pointcut id="pcut" expression="execution(* com.gx.service.impl.*.*(..))" />
    		<aop:advisor advice-ref="txAdvice" pointcut-ref="pcut" />
    	</aop:config>
    
    	<!-- 启动@AspectJ支持(必须否则不生效) -->
    	<aop:aspectj-autoproxy />
    
    	<!-- 注解驱动的声明式事务管理(启用注解事务) -->
    	<tx:annotation-driven transaction-manager="transactionManager" />
    
    </beans>

    spring-datasource.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"
           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">
        
        <!--加载数据源配置文件,ignore-unresolvable配置多处properties必须加-->
        <context:property-placeholder ignore-unresolvable="true" location="classpath:datasource/datasource.properties" />
        
        <!--Master数据源-->
        <bean id="dataSourceMaster" class="com.alibaba.druid.pool.DruidDataSource">
          <property name="driverClassName" value="${jdbc.master.driver_class}"/>
          <property name="url" value="${jdbc.master.url}"/>
          <property name="username" value="${jdbc.master.username}"/>
          <property name="password" value="${jdbc.master.password}"/>
          <property name="initialSize" value="${initialSize}"/>
          <property name="maxActive" value="${maxActive}"/>
          <property name="minIdle" value="${minIdle}"/>
          <property name="maxWait" value="${maxWait}"/>
          <property name="testOnBorrow" value="${testOnBorrow}"/>
        </bean>
      
      	<!--Slave数据源-->
    	<bean id="dataSourceSlave" class="com.alibaba.druid.pool.DruidDataSource">
    	    <property name="driverClassName" value="${jdbc.slave.driver_class}"/>
    	    <property name="url" value="${jdbc.slave.url}"/>
    	    <property name="username" value="${jdbc.slave.username}"/>
    	    <property name="password" value="${jdbc.slave.password}"/>
    	    <property name="initialSize" value="${initialSize}"/>
    	    <property name="maxActive" value="${maxActive}"/>
    	    <property name="minIdle" value="${minIdle}"/>
    	    <property name="maxWait" value="${maxWait}"/>
    	    <property name="testOnBorrow" value="${testOnBorrow}"/>
        </bean>
    	
    	<!-- 配置多数据源 -->
    	<bean id="dataSource" class="com.gx.common.datasource.ThreadLocalRountingDataSource">
            <property name="defaultTargetDataSource" ref="dataSourceMaster" />
            <property name="targetDataSources">
                <map key-type="com.gx.common.datasource.DataSources">
                	<!-- 配置多个dataSource -->
                    <entry key="MASTER" value-ref="dataSourceMaster"/>
                    <entry key="SLAVE" value-ref="dataSourceSlave"/>
                </map>
            </property>
        </bean>      
    	
    </beans>

    spring-redis.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"
           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">
        
        <!--加载数据源配置文件,ignore-unresolvable配置多处properties-->
        <context:property-placeholder ignore-unresolvable="true" location="classpath:datasource/redis.properties" />
        
    	<!-- Redis 配置 -->
    	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    		<property name="maxTotal" value="${redis.maxTotal}" />
    		<property name="maxIdle" value="${redis.maxIdle}" />
    		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
    		<property name="testOnBorrow" value="true" />
    	</bean>
    
    	<!-- redis单节点数据库连接配置 -->
    	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    		<property name="hostName" value="${redis.host}" />
    		<property name="port" value="${redis.port}" />
    		<property name="password" value="${redis.password}" />
    		<property name="poolConfig" ref="jedisPoolConfig" />
    	</bean>
    
    	<!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
    	<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
    		<property name="connectionFactory" ref="jedisConnectionFactory" />
    		<!-- 键格式化字符串 -->
    		<property name="keySerializer">
        		<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        	</property>
        	<!-- 值自动格式化json -->
        	<property name="valueSerializer">
        		<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" ></bean>
        	</property>
        	<!-- 键格式化字符串 -->
    		<property name="hashKeySerializer">
        		<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        	</property>
        	<!-- 值自动格式化json -->
        	<property name="hashValueSerializer">
        		<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" ></bean>
        	</property>
    	</bean>
    	
        <!-- 配置RedisCacheManager -->
        <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
            <constructor-arg index="0" name="redisOperations" ref="redisTemplate" />
            <!-- 默认失效时间(秒) -->
            <property name="defaultExpiration" value="${redis.expiration}" />
        </bean>
    	
    </beans>

    spring-context.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       
        <!--用于管理spring容器相关配置文件(有顺序)-->
        <import resource="spring-datasource.xml" />
        <import resource="spring-mybatis.xml" />
        <import resource="spring-service.xml" />
        <import resource="spring-redis.xml" />
        <import resource="spring-tx.xml" />
      	
    </beans>

    datasource.properties

    # 测试环境
    # 连接数据库(master为insert,update,delete或者实时性要求很高的select语句操作数据库)
    jdbc.master.driver_class = com.mysql.jdbc.Driver
    jdbc.master.url = jdbc:mysql://127.0.0.1:3306/testdb_master?useSSL=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
    jdbc.master.username = root
    jdbc.master.password = root
    # 连接数据库(slave为实时性低的select语句操作数据库)
    jdbc.slave.driver_class = com.mysql.jdbc.Driver
    jdbc.slave.url = jdbc:mysql://127.0.0.1:3306/testdb_slave?useSSL=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
    jdbc.slave.username = root
    jdbc.slave.password = root
    # 配置连接池
    # 初始化连接数
    initialSize = 4
    # 最大连接数
    maxActive = 20
    # 最小连接数
    minIdle = 2
    # 等待时间
    maxWait = 2000
    # 检查连接是否有效
    testOnBorrow = true

    redis.properties

    #redis的服务器地址
    redis.host=127.0.0.1
    #redis的服务端口
    redis.port=6379
    #密码
    redis.password=123
    #链接数据库
    redis.default.db=0
    #客户端超时时间单位是毫秒
    redis.timeout=5000
    #最大连接数
    redis.maxTotal=300
    #最大空闲数
    redis.maxIdle=100
    #最大建立连接等待时间
    redis.maxWaitMillis=1000
    #默认数据失效时间600秒
    redis.expiration=600

    log4j.properties

    # 使用slf4j配置log4j
    ### 设置根记录器 ###
    # ALL、TRACE(跟踪)、DEBUG(调试)、INFO(信息)、WARNING(警告)、ERROR(错误)、FITAL(致命)、OFF等几个级别,级别依次升高。
    # 级别高的Level会屏蔽级别低的信息。
    # stdout:标准输出;Logger打印需要:D,E
    # debug,stdout,D,E
    log4j.rootLogger = info,stdout,D,E
    
    # %d 产生日志的时间
    # %t 产生日志所处的线程名称
    # %-5p 输出日志的级别,将占5位字符,不足5位用空格填补,-指的是在右边补齐,没有则在左边
    # %c 输出日志的包以及类的全名
    # %m 附加的信息
    # %n 换行
    ### 输出信息到控制台 ###
    log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target = System.out
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
    
    ###  按文件大小和按天生成日记文件 ###
    ### 输出 DEBUG 级别以上的日志到=D://logs/redis-demo/log.log ###
    log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.D.File = D://logs/redis-demo/log.log
    log4j.appender.D.Append = true
    log4j.appender.D.Threshold = DEBUG
    log4j.appender.D.layout = org.apache.log4j.PatternLayout
    log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
    
    ### 输出 ERROR 级别以上的日志到=D://logs/redis-demo/error.log ###
    log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.E.File =D://logs/redis-demo/error.log
    log4j.appender.E.Append = true
    log4j.appender.E.Threshold = ERROR
    log4j.appender.E.layout = org.apache.log4j.PatternLayout
    log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
    

    mybatis.cofig.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>
            <!-- 打印查询语句,STDOUT_LOGGING:标准输出日志 -->
            <setting name="logImpl" value="STDOUT_LOGGING" />
            <!-- 开启驼峰映射:就是数据库字段名称类似user_name的需要驼峰映射 -->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
    </configuration>

    代码块(这个内容我就贴主要的实现吧,单单配置博客就长成这样,无奈...所以想要完整的话还是下载demo吧,没积分留个邮箱)

    1、RedisCache.java

    package com.gx.common.util;
    
    import java.util.concurrent.TimeUnit;
    
    import javax.annotation.Resource;
    
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    /**
    * @ClassName: RedisCache 
    * @Description: RedisCache简易工具类注入
    * @author zhoujie 
    * @date 2018年12月12日 下午4:45:16 
    * @version V1.0
     */
    @Component("redisCache") //注册组件
    public class RedisCache {
    
    	@Resource
        private RedisTemplate<String, Object> redisTemplate;
    	
    	/**
         * 将value对象写入缓存
         * @param key
         * @param value
         * @param time 失效时间(秒)
         */
        public void set(String key,Object value,int loseTime){
        	loseTime = loseTime>0?loseTime:600; //设置默认时间600秒
        	redisTemplate.opsForValue().set(key, value, loseTime, TimeUnit.SECONDS); 
        }
        
    	 /**
         * 获取缓存<br>
         * @param key
         * @return
         */
        public Object get(String key){
            return redisTemplate.opsForValue().get(key);
        }
        
    	/**
    	* @Title: del 
    	* @Description: 根据key删除缓存数据
    	* @param @param key
    	* @param @throws Exception 
    	* @return void  
    	* @throws
    	 */
    	public void del(String key) throws Exception {
    		redisTemplate.delete(key);
    	}
    	
    }
    

    DataSourceInterceptor.java

    package com.gx.common.datasource;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    //AOP切面配置数据源
    @Aspect    // for aop
    @Component // for auto scan
    @Order(0)  // execute before @Transactional
    public class DataSourceInterceptor {
    	
    	//切换数据源
        @Pointcut("execution(* com.gx.service.impl.*.get*(..))")
        public void dataSourceSlave(){};
        
        @Before("dataSourceSlave()")
        public void dataSourceSlave(JoinPoint jp) {
        	System.out.println("get*切换数据源Slave");
            DataSourceTypeManager.set(DataSources.SLAVE);
        }
        
        //其他更多设置数据源 ... ...
        //切换数据源2
        @Pointcut("execution(* com.gx.service.impl.*.addBookSlave(..))")
        public void addBookSlave(){};
        
        @Before("addBookSlave()")
        public void addBookSlave(JoinPoint jp) {
        	System.out.println("addBookSlave切换数据源Slave");
            DataSourceTypeManager.set(DataSources.SLAVE);
        }
        
    }
    
    

    DataSources.java

    package com.gx.common.datasource;
    
    /**
     * 数据源的类别:master/slave
     */
    public enum DataSources {
        MASTER, SLAVE
    }
    

    DataSourceTypeManager.java

    package com.gx.common.datasource;
    
    public class DataSourceTypeManager {
    	
    	private static final ThreadLocal<DataSources> dataSourceTypes = new ThreadLocal<DataSources>() {
    		@Override
    		protected DataSources initialValue() {
    			return DataSources.MASTER;
    		}
    	};
    
    	public static DataSources get() {
    		return dataSourceTypes.get();
    	}
    
    	public static void set(DataSources dataSourceType) {
    		dataSourceTypes.set(dataSourceType);
    	}
    
    	public static void reset() {
    		dataSourceTypes.set(DataSources.MASTER);
    	}
    
    }
    

    ThreadLocalRountingDataSource.java

    package com.gx.common.datasource;
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    
    public class ThreadLocalRountingDataSource extends AbstractRoutingDataSource {
    	
        @Override
        protected Object determineCurrentLookupKey() {
        	 System.out.println("数据源:"+DataSourceTypeManager.get());
            return DataSourceTypeManager.get();
        }
        
    }

    BookController.java

    package com.gx.controller;
    
    import com.gx.entity.Book;
    import com.gx.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/book")
    public class BookController {
    
        @Autowired
        private BookService bookService;
    
        @RequestMapping("/list")
        @ResponseBody
        public List<Book> getBooks(){
            return bookService.getBooks();
        }
        
        @RequestMapping("/add")
        @ResponseBody
        public Object addBook(){
        	return bookService.addBook();
        }
        
        @RequestMapping("/add2")
        @ResponseBody
        public Object addBookSlave(){
        	return bookService.addBookSlave();
        }
        
    }
    

    BookService.java

    package com.gx.service;
    
    import com.gx.entity.Book;
    
    import java.util.List;
    
    public interface BookService {
    
    	List<Book> getBooks();
    	
    	int addBook();
    	
    	int addBookSlave();
    	
    }
    

    BookServiceImpl.java

    package com.gx.service.impl;
    
    import com.gx.common.util.RedisCache;
    import com.gx.entity.Book;
    import com.gx.mapper.BookMapper;
    import com.gx.service.BookService;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Date;
    import java.util.List;
    
    import javax.annotation.Resource;
    
    @Service
    public class BookServiceImpl implements BookService {
    	
        @Autowired
        private BookMapper bookMapper;
        
        @Resource
        private RedisCache redisCache; //redis注入,使用就和上面的一样
        
        //get开头的查询slave数据库
    	@SuppressWarnings("unchecked")
    	@Override
        public List<Book> getBooks() {
    		//使用redis,即先到redis中查找是否存在数据,不存在数据再到数据库查询
    		List<Book> list = (List<Book>) redisCache.get("list") ;//获取redis缓存
    		if(list == null){
    			list = bookMapper.selectAll();
    			redisCache.set("list", list, 600); //设置redis缓存
    		}
            return list;
        }
    
    	//新增到master数据库
    	@Override
    	public int addBook() {
    		Book book = new Book();
    		book.setBookDate(new Date());
    		book.setBookName("哈哈1");
    		book.setBookPrice(30.1);
    		return bookMapper.insertSelective(book);
    	}
    
    	//新增到Slave数据库
    	@Override
    	public int addBookSlave() {
    		Book book = new Book();
    		book.setBookDate(new Date());
    		book.setBookName("哈哈2");
    		book.setBookPrice(30.2);
    		return bookMapper.insertSelective(book);
    	}
    	
    }
    

    其余的就部分是生成的,另外的话不重要了

    ok,大体搭建成。。

    测试

    http://localhost:8080/more-datasource/book/list

    http://localhost:8080/more-datasource/book/add

    http://localhost:8080/more-datasource/book/add2

    效果

    redis使用客户端工具查看

    所有切换数据源配置在DataSourceInterceptor.java这个文件里动态配置!!!

    整理不少时间。。。

    下载整合demo

    忘记把客户端工具弄进来了。。

    redis客户端工具

  • 相关阅读:
    ResponsiveSlides.js最轻量级的幻灯片插件
    jQuery.extend 函数详解
    HQL查询语言的使用介绍
    使用Hibernate命名查询
    Jquery.KinSlideshow图片轮播插件
    关于文件下载自己忽略的文件中文命名。。。
    DB2中的ROW_NUMBER() OVER()函数用法
    css ul li 水平布局问题
    彻底弄懂css中单位px和em,rem的区别 转的自己看
    taglib 自定义标签
  • 原文地址:https://www.cnblogs.com/qq1995/p/10358978.html
Copyright © 2020-2023  润新知