redis缓存在实际项目中的简单运用

redis 依赖的jar包:
commons-pool2-2.5.0.jar
jedis-2.9.0.jar
spring-data-redis-1.6.2.RELEASE.jar
我是配合spring4.2实现的缓存操作:我这里实现不在是用redis或则spring cache + redis封装好的缓存  我们这里自己实现需要的缓存数据进行统一缓存 在开发中为了避免脏数据的获取与统一管理缓存数据 我们都是在指定的时间把指定需要进行缓存的数据进行缓存 比如网上的商品数据就是这样实现的 比如每天凌晨把白天需要展示的缓存数据 进行缓存加载在redis里面
我们这里通过配置ShardedJedisPool 实例来实现

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       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-4.2.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
           http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">


<!-- 配置自动识别注解 -->
    <context:component-scan base-package="com.dome" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- <task:annotation-driven/> -->
    <task:annotation-driven executor="asyncExecutor" scheduler="scheduler"/>
  <task:executor id="asyncExecutor" pool-size="100-1000" queue-capacity="10000" rejection-policy="CALLER_RUNS"/>
  <task:scheduler id="scheduler" pool-size="100" />


    <!--加载数据库配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
           <list>
              <!-- 加载数据库连接设置 -->
  <value>classpath:config/database.properties</value>
  <!-- <value>classpath:config/database.properties</value> -->
  <!-- 加载redis连接设置 -->
  <value>classpath:config/redis.properties</value>
          </list>
      </property>
    </bean>
    
<!-- 数据中心连接  就是数据库连接设置 我是封装在一个文件里的  暂不提供-->   
<import resource="datasource-sqlserver.xml" /> 
<!-- redis 缓存设置 redis 连接设置 封装在一个文件里 -->
<import resource="redis_one.xml" />
<!-- 解决使用@ResponseBody 的中文乱码。 --> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <!-- JSON解析对象 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                <property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
                </bean>  
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>text/plain;charset=UTF-8</value>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>
         <!-- 日期格式转换 -->
    <property name="webBindingInitializer">    
        <bean class="com.dome.filter.DateConverterFilter" />    
    </property>    
    </bean>
 
  <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
  <!-- 验证码  kaptcha-->
        <property name="config">  
            <bean class="com.google.code.kaptcha.util.Config">  
                <constructor-arg>  
                    <props>  
                        <prop key="kaptcha.border">yes</prop>  
                        <prop key="kaptcha.border.color">105,179,90</prop>  
                        <prop key="kaptcha.textproducer.font.color">blue</prop>  
                        <prop key="kaptcha.image.width">125</prop>  
                        <prop key="kaptcha.image.height">45</prop>  
                        <prop key="kaptcha.textproducer.font.size">45</prop>  
                        <prop key="kaptcha.session.key">kaptchaRemote</prop>  
                        <prop key="kaptcha.textproducer.char.length">4</prop>  
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
                    </props>  
                </constructor-arg>  
            </bean>  
        </property>  
    </bean>  
</beans>


redis的配置 其他无相关数据源省略 redis_one.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"
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       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-4.2.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
           http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">


    <!-- * 优势:可以配置使用多种不同缓存,比如ehcache+redis
         * 劣势:发现cacheName和key是用一个单独的缓存项实现的,推测其查询一次需要读取两次缓存,效率略低 
                                使用Spring内置CacheManager,内部使用RedisCache对象-->
         
<!-- jedis 配置  连接池配置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />  
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
 
 
<!-- 获取redis连接 设置 1-->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"  scope="singleton">  
      <constructor-arg index="0" ref="poolConfig" />  
      <constructor-arg index="1">  
          <list>  
              <bean class="redis.clients.jedis.JedisShardInfo">  
                  <constructor-arg name="host" value="${redis.host}" />  
              </bean>  
          </list>  
      </constructor-arg>  
  </bean>
</beans>




伪代码验证 按自己需求添加代码 (谨做参考):
控制层:

package com.dome.controller.user;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;


@Controller
@RequestMapping(value = "/user")
public class UserController2 {
// 自己的service层
//@Resource
//private xxxxxService xxxxxService;


@Resource
ShardedJedisPool shardedJedisPool;


@RequestMapping(value="/test")
public Object getOnes(HttpServletRequest request) {
try {
ShardedJedis jed = shardedJedisPool.getResource();
//从redis缓存数据里 加载数据 key=list 这里的key与value的添加 直接去redis客户端添加 这里验证一下 看是否能运行
//可以正常逻辑运行 则最好定一个定时任务 往里面添加需要缓存的数据 则就不要去客户端手动添加啦
String list = (String) jed.get("list");
//判断是否有缓存数据
if(StringUtils.isNotBlank(list)) {
//自己做数据相关转换处理 缓存的数据推荐存储为json格式
System.out.println("list");
}else {
//没有缓存数据 做数据库查询处理
//xxxxxService.相关查询方法;
}
}catch (Exception e) {
//加载缓存数据出错 也做数据库加载操作
//xxxxxService.相关查询方法;
}

return null;
}
}


// 定时任务伪代码 直接用在你定时任务里的方法里即可
// 获取redis对象
//shardedJedisPool=CommonUtil.getCurrentApplicationContext().getBean(ShardedJedisPool.class);
//ShardedJedis jedis = shardedJedisPool.getResource();
// 你需要缓存数据的 service 层实例
//xxxx=CommonUtil.getCurrentApplicationContext().getBean(xxxxService.class);
//xxxx.方法获取数据
//jedis.set("key值","缓存数据 service层获取的数据");




本人觉得 在任务类里定时添加需要缓存的数据 避免了查询脏数据 也方便管理统一的缓存数据 也便于维护



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl+C+V程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值