您的位置:首页 > 数据库 > Redis

strust+spring+redis+sqlite配置

2016-06-17 15:12 621 查看
一、安装

windows下的安装参见:http://os.51cto.com/art/201403/431103.htm

二、需要的jar包





三、配置文件

1、redis.property

<span style="font-size:18px;">#\u4E3B\u673A
redis.host=127.0.0.1
#\u7AEF\u53E3\u53F7
redis.port=6379
#client\u7A7A\u95F2\u591A\u4E45\u65AD\u5F00
redis.timeout=1000
#\u6700\u5927\u80FD\u591F\u4FDD\u6301idel\u72B6\u6001\u7684\u5BF9\u8C61\u6570
redis.maxIdle=500
redis.minIdle=50
redis.maxWait=-1
#\u6700\u5927\u5206\u914D\u7684\u5BF9\u8C61\u6570
redis.maxTotal=10000
#\u591A\u957F\u65F6\u95F4\u68C0\u67E5\u4E00\u6B21\u8FDE\u63A5\u6C60\u4E2D\u7A7A\u95F2\u7684\u8FDE\u63A5
redis.timeBetweenEvictionRunsMillis=30000
#\u7A7A\u95F2\u8FDE\u63A5\u591A\u957F\u65F6\u95F4\u540E\u4F1A\u88AB\u6536\u56DE
redis.minEvictableIdleTimeMillis=100
#\u5F53\u8C03\u7528borrow Object\u65B9\u6CD5\u65F6\uFF0C\u662F\u5426\u8FDB\u884C\u6709\u6548\u6027\u68C0\u67E5
redis.testOnBorrow=true
redis.testWhileIdle=true</span>


redis的各项配置要根据实际需求及设备配置,否则可能影响性能;

2、spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- redis配置 -->
<context:property-placeholder location="/WEB-INF/redis.properties" />

<!-- 参数配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="minIdle" value="${redis.minIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="MaxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
<property name="testWhileIdle" value="${redis.testWhileIdle}" />
</bean>
<!-- 创建redis工厂 -->
<bean id="jedisFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"></property>
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="timeout" value="${redis.timeout}" />
<constructor-arg index="0" ref="jedisPoolConfig" />
</bean>

<bean class="com.pccw.replacega.util.LogRedisTemplate"
id="redisTemplate">
<property name="connectionFactory" ref="jedisFactory"></property>
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
</bean>
</beans>
3、applicationContext.xml

<pre class="html" name="code"><span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<import resource="spring-redis.xml"/>

<!-- 并发测试部分 -->
<bean class="com.pccw.replacega.service.RGATestService" id="logTest">
<!-- <property name="rgaDao" ref="rgaDao"></property> -->
<property name="template" ref="redisTemplate"></property>
</bean>

</beans>
</span>



4、Struts.xml

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- struts的action配置文件 -->
<!-- 将action托管给spring -->
<constant name="struts.objectFactory" value="spring"></constant>
<!-- 所有的action都应该放在对应的package下 -->

<package name="logManage" extends="json-default">

<!-- 并发测试部分 -->
<action name="logTest" class="logTest">
<result name="success" type="json">
<param name="root">returnMsg</param>
</result>
<result name="error" type="json">
<param name="root">returnMsg</param>
</result>
</action>
</package>

</struts>
</span>


5、web.xml

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>LogDemo</display-name>

<!-- 初始化 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 如果有多个文件,在文件之间用英文逗号隔开 -->
<!-- <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-db.xml
</param-value> -->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<!-- 监听器 -->
<!-- 配置spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 定义struts2的核心filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app></span>
三、自定义RedisTemplate

可以使用RedisTemplate.executePipelined()实现批量操作,但很多时候需要自定义返回值,所以需要自定义RedisTemplate。

package com.pccw.replacega.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils;

import com.pccw.replacega.entity.LogDetail;

public class LogRedisTemplate<E,K,V> extends RedisTemplate<K, V> {
@Override
public List<Object> executePipelined(final RedisCallback<?> action,
final   RedisSerializer<?> resultSerializer) {
return execute(new RedisCallback<List<Object>>() {
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
boolean pipelinedClosed = false;
try {
Object result = action.doInRedis(connection);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}
List<Object> closePipeline = connection.closePipeline();
pipelinedClosed = true;
return deserializeMixedResults(closePipeline, getValueSerializer(),getHashKeySerializer(),resultSerializer);
} finally {
if (!pipelinedClosed) {
connection.closePipeline();
}
}
}
});
}

/**
*
* @Title: executeConn
* @Description: 序列化POJO
* @return List<Object>
* @throws
*/
public List<Object> executeConn(final RedisCallback<?> action,final HashMapper<E, K, V> jhm) {
return execute(new RedisCallback<List<Object>>() {
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
boolean pipelinedClosed = false;
try {
Object result = action.doInRedis(connection);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}
List<Object> closePipeline = connection.closePipeline();
pipelinedClosed = true;
return deserializeMixedResults(closePipeline, getHashKeySerializer(),getHashValueSerializer(),jhm);
} finally {
if (!pipelinedClosed) {
connection.closePipeline();
}
}
}
});
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private List<Object> deserializeMixedResults(List<Object> rawValues, RedisSerializer valueSerializer,
RedisSerializer hashKeySerializer, RedisSerializer hashValueSerializer) {
if (rawValues == null) {
return null;
}
List<Object> values = new ArrayList<Object>();
for (Object rawValue : rawValues) {
if (rawValue instanceof byte[] && valueSerializer != null) {
values.add(valueSerializer.deserialize((byte[]) rawValue));
} else if (rawValue instanceof List) {
// Lists are the only potential Collections of mixed values....
values.add(deserializeMixedResults((List) rawValue, valueSerializer, hashKeySerializer, hashValueSerializer));
} else if (rawValue instanceof Set && !(((Set) rawValue).isEmpty())) {
values.add(deserializeSet((Set) rawValue, valueSerializer));
} else if (rawValue instanceof Map && !(((Map) rawValue).isEmpty())
&& ((Map) rawValue).values().iterator().next() instanceof byte[]) {
values.add(SerializationUtils.deserialize((Map) rawValue, hashKeySerializer, hashValueSerializer));
} else {
values.add(rawValue);
}
}
return values;
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private List<Object> deserializeMixedResults(List<Object> rawValues,RedisSerializer hashKeySerializer, RedisSerializer hashValueSerializer,HashMapper<E, K, V> jhm) {
if (rawValues == null) {
return null;
}
List<Object> values = new ArrayList<Object>();
for (Object rawValue : rawValues) {
Map<byte[], byte[]>  obj = (Map<byte[], byte[]>) rawValue;
Map<K, V> map = new LinkedHashMap<K, V>(obj.size());
for (Map.Entry<byte[], byte[]> entry : obj.entrySet()) {
map.put((K) hashKeySerializer.deserialize((entry.getKey())), (V) hashValueSerializer.deserialize((entry.getValue())));
}
values.add(jhm.fromHash(map));
}
return values;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
private Set<?> deserializeSet(Set rawSet, RedisSerializer valueSerializer) {
if (rawSet.isEmpty()) {
return rawSet;
}
Object setValue = rawSet.iterator().next();
if (setValue instanceof byte[] && valueSerializer != null) {
return (SerializationUtils.deserialize((Set) rawSet, valueSerializer));
} else if (setValue instanceof Tuple) {
return convertTupleValues(rawSet, valueSerializer);
} else {
return rawSet;
}
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private Set<TypedTuple<V>> convertTupleValues(Set<Tuple> rawValues, RedisSerializer valueSerializer) {
Set<TypedTuple<V>> set = new LinkedHashSet<TypedTuple<V>>(rawValues.size());
for (Tuple rawValue : rawValues) {
Object value = rawValue.getValue();
if (valueSerializer != null) {
value = valueSerializer.deserialize(rawValue.getValue());
}
set.add(new DefaultTypedTuple(value, rawValue.getScore()));
}
return set;
}

public List<Object> executeConn(final RedisCallback<?> action) {
return execute(new RedisCallback<List<Object>>() {
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
boolean pipelinedClosed = false;
try {
Object result = action.doInRedis(connection);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}
List<Object> closePipeline = connection.closePipeline();
pipelinedClosed = true;
return deserializeMixedResults(closePipeline);
} finally {
if (!pipelinedClosed) {
connection.closePipeline();
}
}
}
});
}

private List<Object> deserializeMixedResults(List<Object> rawValues) {
if (rawValues == null) {
return null;
}
List<Object> values = new ArrayList<Object>();
for (Object rawValue : rawValues) {
if(rawValue instanceof byte[]){
byte[] bs=(byte[])rawValue;
LogDetail logDetail=(LogDetail)RedisHelper.getObjectFromBytes(bs);
values.add(logDetail);
}
}
return values;
}

}


四、参考资料

http://blog.csdn.net/tiantiandjava/article/details/42913691

http://blog.csdn.net/liuzhigang1237/article/details/8283797



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java redis 高并发操作