Springmvc+Redis使用jedisTemplete来操作redis的相关配置和代码示例

来源:互联网 发布:足彩缩水软件 编辑:程序博客网 时间:2024/06/05 07:42

在上一篇当中介绍了一下整合redis的一些配置,那么在本章中主要是对于配置jedisTemplete来做一下简述,废话不多,直接上配置和代码

1.redis.properties

 url=10.4.13.30
port=6379
maxTotal=4096
maxIdle=128
maxWaitMillis=3000
testOnBorrow=true
testOnReturn=true

2.springMVC.xml

<!-- 加载propertise属性配置 -->
<context:property-placeholder location="classpath:redis.properties"/>

<!-- 配置redis -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${maxTotal}" />
<property name="maxIdle" value="${maxIdle}" />
<property name="maxWaitMillis" value="${maxWaitMillis}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
</bean>

<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${url}"/>  
        <property name="port" value="${port}"/>
        <property name="poolConfig" ref="poolConfig"/>
</bean>

<!-- redis操作模板,这里采用尽量面向对象的模板 -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory" ref="connectionFactory" />  
    <!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  
        <property name="keySerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
        </property>  
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>  
    </bean>     

3.使用简单说明

直接注解

@Resource
private RedisTemplate redisTemplate;

List<Product> productList = redisTemplate.opsForList().range("product", 0, -1);
if(productList.size() > 0){
return productList;
}
else{
ProductExample example = new ProductExample();
example.setOrderByClause("productname");
List<Product> products = productMapper.selectByExample(example);
redisTemplate.opsForList().leftPushAll("product", products);
return products;
}

原创粉丝点击