PAODING-ROSE与Redis集成
Rose简介:人人网、糯米网释出的、开源的高效Java web开发框架。在小米米聊服务端再次被验证和使用。一个从零开始的创业公司,在大家技术背景不一的情况下,rose很简单快速地传达到了大家中间。本手册致力于让php开发人员也能快速使用上java开发高性能服务。
开发环境
- IDEA 13.1.1
- JDK 1.7.0_60
添加项目依赖
<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.search.sms</groupId>
<artifactId>search</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>search</name>
<url>http://maven.apache.org</url>
<properties>
<servlet.version>3.0.1</servlet.version>
<spring.version>3.2.0.RELEASE</spring.version>
<project.build.sourceEncoding>GBK</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- paoding rose start -->
<dependency>
<groupId>net.paoding</groupId>
<artifactId>paoding-rose-load</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>net.paoding</groupId>
<artifactId>paoding-rose-web</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>net.paoding</groupId>
<artifactId>paoding-rose-jade</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.54chen</groupId>
<artifactId>paoding-rose-scanning</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.paoding</groupId>
<artifactId>paoding-rose</artifactId>
<version>2.0</version>
</dependency>
<!-- paoding rose end -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<!-- spring begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-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-aop</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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<!-- spring end -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- redis client -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.11</version>
</dependency>
</dependencies>
<build>
<finalName>search</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Rose>*</Rose>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置web.xml
<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>search</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<filter>
<filter-name>roseFilter</filter-name>
<filter-class>net.paoding.rose.RoseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>roseFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</web-app>
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-lazy-init="true">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:*.properties</value>
</list>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="com.itcc8.sms.wechat"></context:component-scan>
<bean id="jade.dataSource.com.itcc8.sms.wechat.dao" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="50" />
<property name="maxWait" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<property name="filters" value="stat" />
</bean>
<!--
<import resource="classpath:dubbo-demo-provider.xml"/>
-->
<import resource="classpath:applicationContext-redis.xml"/>
<import resource="classpath:applicationContext-aop.xml"/>
</beans>
applicationContext-aop.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
">
<aop:aspectj-autoproxy proxy-target-class="false" />
</beans>
applicationContext-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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" default-autowire="byName">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxTotal" value="${redis.pool.maxActive}" />
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
</bean>
<!-- Redis template definition for default database -->
<bean id="jedisConnectionFactoryForDefaultDB"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"/>
<property name="hostName" value="${redis.ip}"/>
<property name="port" value="${redis.port}"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
<property name="database" value="0"/>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connectionFactory-ref="jedisConnectionFactoryForDefaultDB">
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
</beans>
redis.properties
redis.pool.maxActive=1024
redis.pool.maxIdle=200
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
#IP
redis.ip=Redis服务器IP
#Port 默认端口号
redis.port=6379
项目结构
目录结构说明
- aop:自定义缓存注解,例如本例中带有Cacheable 注解将通过redis实现缓存,例:
package com.itcc8.sms.wechat.service;
import org.springframework.stereotype.Service;
import com.itcc8.sms.wechat.aop.CacheKey;
import com.itcc8.sms.wechat.aop.Cacheable;
@Service
public class TCacheService {
//Cacheable 标注为此注解将通过redis实现缓存 exire 过期时间 单位:秒 TimeUnit.SECONDS
@Cacheable(expire=3) //CacheKey 标注为此注解实现key的缓存
public String cached(@CacheKey String requestParam) {
// return "@json:"+new Object();
// return "/view.html";
return "@success";
}
}
- cache:CacheService示例可以在程序中灵活读取、删除、存储对象到redis中,例:
package com.itcc8.sms.wechat.cache;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
//(把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
@Component
public class CacheService {
private final static Logger logger = Logger.getLogger(CacheService.class);
@Autowired
private RedisTemplate<String, Object> redisTemplateForDefaultDB;
public void saveForValue(String key, Object object, long activeTime) {
try {
redisTemplateForDefaultDB.opsForValue().set(key, object, activeTime, TimeUnit.MINUTES);
} catch (Exception e) {
logger.error(String.format("redis set operation for value failed by key [%s]: %s", key, e.getMessage()), e);
return;
}
}
public Object readForValue(String key) {
Object object = null;
String i = "";
try {
object = redisTemplateForDefaultDB.opsForValue().get(key);
} catch (Exception e) {
logger.error(String.format("redis get operation for value failed by key [%s]: %s", key, e.getMessage()), e);
return object;
}
return object;
}
public boolean delKey(String model) {
boolean result = false;
try {
Set<String> keySet = redisTemplateForDefaultDB.keys(model);
if (keySet != null && keySet.size() > 0)
redisTemplateForDefaultDB.delete(keySet);
result = true;
} catch (Exception e) {
logger.error("redis get operation for value failed by key [%s]: %s" + model, e);
result = false;
} finally {
return result;
}
}
public void setRedisTemplateForDefaultDB(RedisTemplate<String, Object> redisTemplateForDefaultDB) {
this.redisTemplateForDefaultDB = redisTemplateForDefaultDB;
}
}
- controllers:rose规定所有拦截器所在的位置,例:
package com.itcc8.sms.wechat.controllers;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import com.itcc8.sms.wechat.service.TCacheService;
import com.itcc8.sms.wechat.util.HttpServletUtil;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
@Path("/cache")
public class TestCacheController {
@Autowired
private TCacheService servive;
@Get("t1")
public String doGet(HttpServletRequest request) throws IOException {
return servive.cached(HttpServletUtil.getReqParam(request));
}
}
- DAO:dao层接口位置,ROSE规定所有类文件必须以大写DAO结尾,例:
package com.itcc8.sms.wechat.dao;
import com.itcc8.sms.wechat.model.MtMessage;
import com.itcc8.sms.wechat.model.MtReport;
import net.paoding.rose.jade.annotation.DAO;
import net.paoding.rose.jade.annotation.SQL;
import net.paoding.rose.jade.annotation.SQLParam;
import java.util.List;
@DAO
public interface ImtHistoryDAO {
@SQL("SELECT a.userId,b.name as userName,b.availableMt as userAmt,a.historyId,a.availableId,a.mtContent,a.phone,a.sendTime,a.batchId,a.gatewayId,a.status,a.mtResponse,a.mtReport,a.reportTime,a.createTime,a.cpSeq " +
" FROM plat_mt_history a,plat_user b" +
" WHERE" +
" a.phone = :phone and a.userId = b.id ORDER BY historyId DESC lIMIT :start,:length")
public List<MtMessage> searchMsgByPhoneNumber(@SQLParam("phone") String phone, @SQLParam("start") int start, @SQLParam("length") int length);
@SQL("SELECT count(1) " +
" FROM plat_mt_history a " +
" WHERE" +
" a.phone = :phone ")
public int getMsgSizeByPhoneNumber(@SQLParam("phone") String phone);
@SQL("SELECT a.userId,b.name as userName,b.availableMt as userAmt,a.historyId,a.availableId,a.mtContent,a.phone,a.sendTime,a.batchId,a.gatewayId,a.status,a.mtResponse,a.mtReport,a.reportTime,a.createTime,a.cpSeq " +
" FROM plat_mt_history a,plat_user b" +
" WHERE" +
" a.historyId = :historyId lIMIT 1")
public MtMessage searchMsgById(@SQLParam("historyId") long historyId);
@SQL("SELECT count(1) " +
" FROM plat_mt_history a " +
" WHERE" +
" a.historyId = :historyId ")
public int getMsgById(@SQLParam("historyId") long historyId);
@SQL("select b.gatewayId,b.mtReport,count(1) as count from plat_mt_history b "
+" where createTime>=:startDate and createTime<:endDate"
+ " group by b.gatewayId,b.mtReport order by b.gatewayId asc")
public List<MtReport> queryStatistics4Report(@SQLParam("startDate") String startDate, @SQLParam("endDate") String endDate);
@SQL("select b.gatewayId, count(1) as count from plat_mt_history b "
+" where createTime>=:startDate and createTime<:endDate"
+ " group by b.gatewayId order by b.gatewayId asc")
public List<MtReport> queryStatistics4Count(@SQLParam("startDate") String startDate, @SQLParam("endDate") String endDate);
@SQL("select b.gatewayId, count(1) as count,b.userId,a.name from plat_mt_history b,plat_user a "
+" where b.createTime>=:startDate and b.createTime<:endDate and a.id=b.userId "
+ " group by b.gatewayId,b.userId,a.name order by b.gatewayId asc")
public List<MtReport> queryStatistics4User(@SQLParam("startDate") String startDate, @SQLParam("endDate") String endDate);
}