springMVC4+spring4+hibernate4框架搭建
最近项目不是很忙,整理了一个springMVC框架给大家分享下,框架结构:springMVC4+spring4+hibernate4,主要是spring配置、springmvc配置、hibernate配置,数据库连接和redis缓存配置,以及声明式缓存的配置,还有就是HibernateTemplate(hibernate4)的注入.。
项目结构
maven项目的pom文件: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>com.example</groupId> <artifactId>maven-springmvc</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>springmvc</name> <url>http://maven.apache.org</url> <properties> <springVersion>4.3.1.RELEASE</springVersion> <hibernateVersion>4.3.5.Final</hibernateVersion> <jstlVersion>1.2</jstlVersion> <taglibVersion>1.1.2</taglibVersion> <servletVersion>3.0-alpha-1</servletVersion> <jsonVersion>1.9.13</jsonVersion> <jacksonVersion>2.5.0</jacksonVersion> <mysqlVersion>5.1.38</mysqlVersion> <c3p0Version>0.9.1.2</c3p0Version> <log4jVersion>1.2.17</log4jVersion> <fileuploadVersion>1.3.1</fileuploadVersion> <lombokVersion>1.16.10</lombokVersion> </properties> <!--项目依赖 --> <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <!-- spring web + spring MVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springVersion}</version> </dependency> <!-- hibernate配置--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- hibernate 缓存 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernateVersion}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- jsp页面使用的jstl支持--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlVersion}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibVersion}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servletVersion}</version> <scope>provided</scope> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <!-- 数据库连接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0Version}</version> </dependency> <!-- redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.0.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <!-- Java对象转换成json对象--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonVersion}</version> </dependency> <!-- log4j配置, 视情况添加--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jVersion}</version> </dependency> <!--文件 上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadVersion}</version> </dependency> <!-- lombok插件导包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombokVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.0</version> </dependency> </dependencies> <build> <finalName>springmvc</finalName> <resources> <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resources目录下--> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>${basedir}/src/main/resources</directory> </resource> </resources> <plugins> <!--servlet容器 jetty插件--> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.10.v20160621</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webApp> <contextPath>/springmvc</contextPath> </webApp> <httpConnector> <port>8082</port> </httpConnector> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app 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" version="3.0"> <!--welcome pages--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--加载Spring的配置文件到上下文中去--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <!-- spring MVC config start--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此处指向的的是SpringMVC的配置文件 --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!--配置容器在启动的时候就加载这个servlet并实例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring MVC config end--> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 字符集过滤 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
spring配置和hibernate配置以及事务管理:applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.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-4.3.xsd"> <!--***************************配置Spring*******************--> <!-- 自动扫描 --> <context:component-scan base-package="com.example"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--*************************配置hibernate******************--> <!--扫描配置文件(这里指向的是之前配置的那个config.properties)--> <context:property-placeholder location="classpath:config.properties" /> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动--> <property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址--> <property name="user" value="${jdbc.username}" /> <!--用户名--> <property name="password" value="${jdbc.password}" /> <!--密码--> <property name="maxPoolSize" value="40" /> <!--最大连接数--> <property name="minPoolSize" value="1" /> <!--最小连接数--> <property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接--> <property name="maxIdleTime" value="20" /> <!--最大空闲时间--> </bean> <!--配置session工厂--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.example.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表--> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言--> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句--> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)--> </props> </property> </bean> <!-- 配置spring的声明性事务 --> <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager"><!-- 要根据hibernate的版本配置 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置事务属性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 配置事务切入点 --> <aop:config proxy-target-class="true"> <aop:pointcut expression="execution(* com.example.base.*.*(..))" id="pointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/> </aop:config> <!-- 配置 HibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 引入同文件夹下的redis属性配置文件 --> <import resource="redis-context.xml"/> </beans>
数据库和hibernate配置信息:config.properties
#database connection config jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/data_springmvc?useSSL=false&characterEncoding=utf-8 jdbc.username = root jdbc.password = root #hibernate config hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = true hibernate.format_sql = true hibernate.hbm2ddl.auto = update
springMVC配置: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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!--********************************************配置springMVC***************************************--> <!-- 自动扫描 --> <mvc:annotation-driven /> <context:component-scan base-package="com.example.controller" /> <aop:aspectj-autoproxy proxy-target-class="true"/> <mvc:annotation-driven/> <!-- @ResponseBody 数据集合的转换--> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP--> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- springmvc文件上传需要配置的节点--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20971500"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> </beans>
日志配置:log4j.properties
#配置根Logger 后面是若干个Appender log4j.rootLogger=INFO,A1,R #log4j.rootLogger=INFO,A1,R # ConsoleAppender 输出 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n # File 输出 一天一个文件,输出路径可以定制,一般在根路径下 log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.File=log.txt log4j.appender.R.MaxFileSize=500KB log4j.appender.R.MaxBackupIndex=10 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
redis缓存配置:redis-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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="300" /> <property name="maxActive" value="600" /> <property name="maxWait" value="1000" /> <property name="testOnBorrow" value="true" /> </bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="127.0.0.1" p:port="6379" p:password="" p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> </bean> </beans>
HibernateTemplate的注入
package com.example.base; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.*; import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.orm.hibernate4.HibernateTemplate; import javax.annotation.Resource; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by ypf on 2018/12/26. */ public class GenericDaoHibenate<T,PK extends Serializable> implements GenericDao<T,PK>{ protected final Log log = LogFactory.getLog(getClass()); protected Class<T> persistentClass; public GenericDaoHibenate(Class<T> persistentClass) { this.persistentClass = persistentClass; } @Resource(name = "hibernateTemplate") private HibernateTemplate hibernateTemplate; public T get(PK id) { T entity = hibernateTemplate.get(this.persistentClass, id); Hibernate.initialize(entity); if (entity == null) { log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found..."); throw new ObjectRetrievalFailureException(this.persistentClass, id); } return entity; } public T save(T object) { return hibernateTemplate.merge(object); } public void saveOrUpdate(T object) { hibernateTemplate.saveOrUpdate(object); } public void remove(PK id) { hibernateTemplate.delete(this.get(id)); hibernateTemplate.flush(); } public void update(T object) { hibernateTemplate.update(object); } public boolean exists(PK id) { T entity = hibernateTemplate.get(this.persistentClass, id); return entity != null; } public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) { String[] params = new String[queryParams.size()]; Object[] values = new Object[queryParams.size()]; int index = 0; Iterator<String> i = queryParams.keySet().iterator(); while (i.hasNext()) { String key = i.next(); params[index] = key; values[index++] = queryParams.get(key); } return (List<T>)hibernateTemplate.findByNamedQueryAndNamedParam(queryName,params,values); } public Long countSql(String sql) { Session session = getSession(); Query query = session.createQuery(sql); long ret = ((Long) query.uniqueResult()).longValue(); releaseSession(session); return ret; } public Long countSql(String sql, Object[] parms) { return null; } public List querySql(String sql) { return null; } public List querySql(String sql, Object[] parms) { return null; } public List querySql(String sql, int start, int limit) { return null; } public List querySql(String sql, Object[] parms, int start, int limit) { return null; } public List querySql(String sql, Map<String, Object> params) { return null; } public List querySql(String sql, Map<String, Object> params, int start, int limit) { return null; } public boolean executeSql(String sql) { return false; } public boolean executeSql(String sql, Object[] parms) { return false; } private Session getSession(){ Session session = hibernateTemplate.getSessionFactory().openSession(); return session; } private void releaseSession(Session session){ if(session != null){ session.close(); } } }
redis缓存工具类
package com.example.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; @Component public class RedisManager { private final Logger logger = LoggerFactory.getLogger(RedisManager.class); @SuppressWarnings("rawtypes") @Autowired private RedisTemplate redisTemplate; /** * 批量删除对应的value * * @param keys */ public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * 批量删除key * * @param pattern */ @SuppressWarnings("unchecked") public void removePattern(final String pattern) { Set<Serializable> keys = redisTemplate.keys(pattern); if (keys.size() > 0) redisTemplate.delete(keys); } /** * 删除对应的value * * @param key */ @SuppressWarnings("unchecked") public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判断缓存中是否有对应的value * * @param key * @return */ @SuppressWarnings("unchecked") public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 读取缓存 (String) * * @param key * @return */ @SuppressWarnings("unchecked") public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } /** * 写入缓存 (String) * * @param key * @param value * @return */ @SuppressWarnings("unchecked") public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 (String) * * @param key * @param value * @param expireTime * @return */ @SuppressWarnings("unchecked") public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public boolean set(final String key, Object value, Long expireTime,int type) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 (List)单个值写入可设置缓存时间 * * @param key * @param value * @param expireTime * @return */ @SuppressWarnings("unchecked") public boolean rightPush(final String key, Object value, Long expireTime) { boolean result = false; try { ListOperations<Serializable, Object> operations = redisTemplate.opsForList(); operations.rightPush(key, value); //设置缓存时间 if(expireTime > 0){ redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); } result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 (List)批量写入 * * @param key * @param values * @param expireTime * @return */ @SuppressWarnings("unchecked") public boolean rightPushAll(final String key, Long expireTime, List<Object> values) { boolean result = false; try { ListOperations<Serializable, Object> operations = redisTemplate.opsForList(); for(Object value:values){ operations.rightPush(key, value); } if(expireTime > 0){ redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); } result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 读取缓存 (List)(全部) * * @param key * @return */ @SuppressWarnings("unchecked") public List<Object> rangeAll(final String key) { List<Object> result = new ArrayList<Object>(); try { ListOperations<Serializable, Object> operations = redisTemplate.opsForList(); result = operations.range(key,0,-1); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 读取缓存 (List) * * @param key * @param start * @param end * @return */ @SuppressWarnings("unchecked") public List<Object> range(final String key,long start,long end) { List<Object> result = new ArrayList<Object>(); try { ListOperations<Serializable, Object> operations = redisTemplate.opsForList(); result = operations.range(key,start,end); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 删除list中的value (List) * * @param key * @param count * count > 0:删除等于从头到尾移动的值的元素。 count < 0:删除等于从尾到头移动的值的元素。 count = 0:删除等于value的所有元素。 * @param value * @return */ @SuppressWarnings("unchecked") public void removeListValue(final String key,long count,String value) { try { if(exists(key)){ ListOperations<Serializable, Object> operations = redisTemplate.opsForList(); operations.remove(key,count,value); } } catch (Exception e) { e.printStackTrace(); } } }
测试类TestController
package com.example.controller; import com.example.model.User; import com.example.service.UserManager; import com.example.util.RedisManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by ypf on 2018/12/24. */ @Controller @RequestMapping("/test") public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); @Autowired private RedisManager redisManager; @Autowired private UserManager userManager; public static String RESULT_CODE = "resultCode"; public static String RESULT_MSG = "resultMsg"; @RequestMapping("/index") public String index(){ return "index"; } @RequestMapping("/hello") @ResponseBody public String hello(HttpServletRequest request){ logger.info("url:" + request.getPathInfo()); logger.info("url:" + request.getRequestURI()); logger.info("url:" + request.getRequestURL()); return "hello world"; } @RequestMapping("/redis") @ResponseBody public String test(String key,String value){ redisManager.set(key,value); String result = redisManager.get(key).toString(); return result; } @RequestMapping("/getUserInfo") @ResponseBody public User getUserInfo(Long id){ User user = userManager.get(id); return user; } @RequestMapping("/saveUserInfo") @ResponseBody public Map<String,Object> saveUserInfo(String name){ Map<String,Object> map = new HashMap<String, Object>(); User user = new User(); user.setUsername(name); user.setPassword("123456"); user.setLoginTime(new Date()); userManager.save(user); map.put(RESULT_CODE,"200"); map.put(RESULT_MSG,"success"); map.put("userInfo",user); return map; } }
由于文件比较多,这里就不一一列举了,下面为测试结果: