spring整合SpringMVC+Mybatis+ehcache+quartz

这个算是老调重弹了,网上很多。


spring就不用说了。大家都很熟悉,用得也多。

Mybatis是个半自动ORM框架,相比hibernate,个人更喜欢用Mybatis,主要还是方便对SQL的控制吧。

ehCache是个JVM缓存框架,非常小,但性能非常好。这边整合进来主要是用来对SQL结果进行缓存。

quartz是由java编写的开源作业调度框架,用这个主要是为了方便集群。很多场合直接使用timer 也能完成。


用到的jar这里就不列举了,网上很容易就能找到。主要还是看看怎么配置,注释都先得很清楚了。


先看看配置文件(有几个这里没有介绍的请忽略):





首先添加spring配置文件


<?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" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.1.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 
     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

	<!-- 读取数据库配置文件 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

	<!-- 设置dataSource -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClass}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="${dbcp.maxActive}" />
		<property name="maxIdle" value="${dbcp.maxIdle}" />
		<property name="maxWait" value="${dbcp.maxWait}" />
		<property name="defaultAutoCommit" value="true" />
	</bean>

	<!-- 设置MyBatis数据源,这样就不需要每个文件都要单独配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:MyBatisSetting.xml" />
		<property name="mapperLocations" value="classpath*:mapper/*.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>


	<!-- 配置数据库事务,你懂的 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 配置哪些操作需要进行事务处理 -->
	<bean id="transactionInterceptor"
		class="org.springframework.transaction.interceptor.TransactionInterceptor">
		<property name="transactionManager" ref="transactionManager" />
		<property name="transactionAttributes">
			<props>
				<prop key="remove*">PROPAGATION_REQUIRED</prop>
				<prop key="add*">PROPAGATION_REQUIRED</prop>
				<prop key="modify*">PROPAGATION_REQUIRED</prop>
				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="search*">PROPAGATION_REQUIRED,readOnly</prop>
			</props>
		</property>
	</bean>

	<!-- 自动代理事务,这样你就不需要每个service去配置事务啦 -->
	<bean id="autoproxy"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="beanNames">
			<list>
				<value>*Service</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>transactionInterceptor</value>
				<!--<value>loggerInterceptor</value> -->
			</list>
		</property>
	</bean>


	<!-- 配置支持chcache缓存 -->
	<cache:annotation-driven cache-manager="ehcacheCacheManager" />
	<bean id="ehcacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<property name="cacheManager" ref="ehcacheManager" />
	</bean>

	<bean id="ehcacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:ehcache/ehcache.xml" />
	</bean>


	<!--<bean id="loggerInterceptor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 
		<property name="advice" ref="actionLogger" /> <property name="patterns"> 
		<value>.*</value> </property> </bean> -->


	<!-- 导入quartz配置的文件 -->
	<import resource="spring-quartz.xml" />


</beans>


quartz配置文件


<?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" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-3.1.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-3.1.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 
     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">


	<!-- 要调用的工作类 -->
	<bean id="ehCacheQuartzJob" class="com.push.socket.quartz.EhCacheQuartzJob" />
	<bean id="redisQuartzJob" class="com.push.socket.quartz.RedisQuartzJob" />

	<!-- 定义一级缓存调用对象和调用对象的方法 -->
	<bean id="ehCacheQuartzJobTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!-- 调用的类 -->
		<property name="targetObject">
			<ref bean="ehCacheQuartzJob" />
		</property>
		<!-- 调用类中的方法 -->
		<property name="targetMethod">
			<value>ehCacheWork</value>
		</property>
	</bean>

	<!-- 定义一级缓存触发时间 -->
	<bean id="cronTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail">
			<ref bean="ehCacheQuartzJobTask" />
		</property>
		<!-- cron表达式 -->
		<property name="cronExpression">
			<value>5/20 * * * * ?</value>
		</property>
	</bean>


	<!-- 定二级缓存调用对象和调用对象的方法 -->
	<bean id="redisQuartzJobTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!-- 调用的类 -->
		<property name="targetObject">
			<ref bean="redisQuartzJob" />
		</property>
		<!-- 调用类中的方法 -->
		<property name="targetMethod">
			<value>redisWork</value>
		</property>
	</bean>

	<!-- 定义二级缓存触发时间 -->
	<bean id="redisTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail">
			<ref bean="redisQuartzJobTask" />
		</property>
		<!-- cron表达式 -->
		<property name="cronExpression">
			<value>5/30 * * * * ?</value>
		</property>
	</bean>


	<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
	<bean id="startQuertz" lazy-init="false" autowire="no"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<!-- 读取配置 -->
		<property name="configLocation" value="classpath:quartz.properties" />
		<property name="triggers">
			<list>
				<ref bean="cronTrigger" />
				<ref bean="redisTrigger" />
			</list>
		</property>
	</bean>

</beans>


springMVC配置文件


<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<!-- 启用spring mvc 注解 ,配置了component-scan就可以把这个去掉 -->
	<!--<context:annotation-config /> -->


	<!-- 设置使用注解的类所在的jar包,设置自动扫描 -->
	<context:component-scan base-package="com.push.controller" />


	<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>


	<!-- 完成请求和注解POJO的映射 -->

	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<!-- 需要加上order属性,不然让其他的handler先处理了,就访问不到了 -->
		<property name="order" value="0" />
	</bean>

	<!-- 配置页面返回JSON,springMVC本身支持直接返回json,你也可以返回到一个JSP页面 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!-- 设置json编码格式为UTF-8 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>


	<!-- 配置上传文件 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为10MB -->
		<property name="maxUploadSize">
			<value>10485760</value>
		</property>
	</bean>


	<!-- 配置对静态资源的访问 -->
	<mvc:resources location="/static/" mapping="/static/**" />
	
	
	<!-- 导入配置拦截器的文件 -->
	<import resource="springMVC-interceptro.xml" />

</beans>

spring 拦截器配置文件


<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">


	<!-- 配置拦截器 -->
	<mvc:interceptors>
		<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->



		<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的,这里用来用户登录权限拦截 -->
		<mvc:interceptor>
			<mvc:mapping path="/pushEntity/*" />
			<!-- 要把bean写在最后面 -->
			<bean class="com.push.interceptor.LoginPermissionInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

</beans>

ehCache配置文件:


<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  

<diskStore path="java.io.tmpdir/ehcache"/>  

<!-- service 缓存配置 -->
<cache name="serviceCache"
	eternal="false"  
    maxElementsInMemory="2000" 
    maxElementsOnDisk="2000"
    overflowToDisk="false" 
    diskPersistent="false"  
    timeToIdleSeconds="1800" 
    timeToLiveSeconds="3600"  
    memoryStoreEvictionPolicy="LRU" /> 
</ehcache> 



<!-- 
参数说明:

<diskStore>:当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)。

<diskStore path="">:用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index。

name:缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)。

maxElementsOnDisk:磁盘缓存中最多可以存放的元素数量,0表示无穷大。

maxElementsInMemory:内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况。

1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中。

2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素。

Eternal:缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds。

timeToIdleSeconds:缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除。

timeToLiveSeconds:缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大,即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除。

overflowToDisk:内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中),会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data。

diskPersistent:是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。

diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔,默认是120秒。

diskSpoolBufferSizeMB:设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB

memoryStoreEvictionPolicy:内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存,共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)。


 -->

myBatis配置文件:

<?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>


	<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
	<settings>

		<!-- 全局映射器启用缓存 -->
		<setting name="cacheEnabled" value="true" />

		<!-- 查询时,关闭关联对象即时加载以提高性能 -->
		<setting name="lazyLoadingEnabled" value="false" />

		<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
		<setting name="multipleResultSetsEnabled" value="true" />

		<!-- 允许使用列标签代替列名 -->
		<setting name="useColumnLabel" value="true" />

		<!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->
		<setting name="autoMappingBehavior" value="PARTIAL" />

		<!-- 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE -->
		<!-- <setting name="defaultExecutorType" value="BATCH" /> -->

		<!-- 数据库超过25000秒仍未响应则超时 -->
		<!-- <setting name="defaultStatementTimeout" value="25000" /> -->

		<!-- Allows using RowBounds on nested statements -->
		<setting name="safeRowBoundsEnabled" value="false" />

		<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
		<setting name="aggressiveLazyLoading" value="false" />

	</settings>

	<typeAliases>
		<!-- 分页 -->
		<typeAlias type="com.push.plugin.Page" alias="Page" />
	</typeAliases>

	<plugins>
		<!-- com.github.pagehelper为PageHelper类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<property name="dialect" value="mysql" />
			<!-- 该参数默认为false -->
			<!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
			<!-- 和startPage中的pageNum效果一样 -->
			<property name="offsetAsPageNum" value="true" />
			<!-- 该参数默认为false -->
			<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
			<property name="rowBoundsWithCount" value="true" />
			<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
			<!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) -->
			<property name="pageSizeZero" value="true" />
			<!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
			<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
			<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
			<property name="reasonable" value="false" />
			<!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
			<!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
			<!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->
			<!-- 不理解该含义的前提下,不要随便复制该配置 <property name="params" value="pageNum=start;pageSize=limit;" 
				/> -->
		</plugin>
	</plugins>


</configuration>


quartz.properties

# 配置主调度器属性  
org.quartz.scheduler.instanceName = QuartzScheduler  
org.quartz.scheduler.instanceId  = AUTO  
# 配置线程池  
# Quartz线程池的实现类  
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool  
# 线程池的线程数量  
org.quartz.threadPool.threadCount = 1  
# 线程池里线程的优先级  
org.quartz.threadPool.threadPriority = 5  
# 配置作业存储  
org.quartz.jobStore.misfireThreshold = 60000  
org.quartz.jobStore.class =org.quartz.simpl.RAMJobStore


web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name>PushServer</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Spring刷新Introspector防止内存泄露 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- Spring MVC配置 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springMVC-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


	<!-- 字符编码 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!--log4j配置文件加载 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<!--spring log4j监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>


	<!-- 开启socket接收引擎 -->
	<listener>
		<listener-class>com.push.socket.main.LaunchScoketEngine</listener-class>
	</listener>

</web-app>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值