redis是现在主流的缓存工具了,因为使用简单、高效且对服务器要求较小,用于大数据量下的缓存

spring也提供了对redis的支持: org.springframework.data.redis.core.RedisTemplate

为了在springmvc环境中使用redis,官方推荐是和jedis结合使用,由jedis来管理连接这些

首先进行整合配置

1.properties文件

#############Common Redis configuration
cache.redis.maxIdle=5
cache.redis.maxActive=20
cache.redis.maxWait=1000
cache.redis.testOnBorrow=true ##############Redis configuration
cache.redis.host=127.0.0.1
cache.redis.port=6379
cache.redis.password=
cache.redis.db=0
cache.redis.timeout=2000 ##############
cache.cacheExpire=500

2.xml配置文档

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${cache.redis.maxActive}" />
<property name="maxIdle" value="${cache.redis.maxIdle}" />
<property name="maxWaitMillis" value="${cache.redis.maxWait}" />
<property name="testOnBorrow" value="${cache.redis.testOnBorrow}" />
</bean> <bean id="redisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"></property>
<property name="hostName" value="${cache.redis.host}" />
<property name="port" value="${cache.redis.port}" />
<property name="password" value="${cache.redis.password}" />
<property name="timeout" value="${cache.redis.timeout}" />
<property name="database" value="${cache.redis.db}"></property>
<constructor-arg index="0" ref="jedisPoolConfig" />
</bean> <bean id="redisCache" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisConnectionFactory" />
<property name="keySerializer" ref="stringRedisSerializer" />
<property name="valueSerializer" ref="stringRedisSerializer" />
<property name="hashKeySerializer" ref="stringRedisSerializer" />
<property name="hashValueSerializer" ref="stringRedisSerializer" />
</bean> <bean id="stringRedisSerializer"
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</beans>

3.使用实例之,存入到redis

package net.zicp.xiaochangwei.web.cache;

import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import net.zicp.xiaochangwei.web.dao.CityDao;
import net.zicp.xiaochangwei.web.dao.FeedBackDao;
import net.zicp.xiaochangwei.web.dao.HobbyDao;
import net.zicp.xiaochangwei.web.dao.PhotoDao;
import net.zicp.xiaochangwei.web.dao.RolePermissionDao;
import net.zicp.xiaochangwei.web.dao.UserDao;
import net.zicp.xiaochangwei.web.entity.City;
import net.zicp.xiaochangwei.web.entity.Hobby;
import net.zicp.xiaochangwei.web.entity.HobbyType;
import net.zicp.xiaochangwei.web.entity.Permission;
import net.zicp.xiaochangwei.web.entity.Photos;
import net.zicp.xiaochangwei.web.entity.Role;
import net.zicp.xiaochangwei.web.entity.UserInfo;
import net.zicp.xiaochangwei.web.utils.Constant;
import net.zicp.xiaochangwei.web.utils.NamedThreadFactory; import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; /**
*
* @author xiaochangwei
* redis缓存变动较少的数据并定时刷新
*/
@Component
public class BasicDataCacheLoader implements InitializingBean, DisposableBean { private final Logger log = LoggerFactory.getLogger(this.getClass()); protected static final int CORE_SIZE = Runtime.getRuntime().availableProcessors() * 2; @Value("${cache.cacheExpire}")
private long cacheExpire; private ScheduledThreadPoolExecutor executor = null; @Autowired
private RedisTemplate<String, String> redisCache; @Autowired
private FeedBackDao feedBackDao; @Autowired
private RolePermissionDao rolePermissionDao; @Autowired
private CityDao cityDao; @Autowired
private HobbyDao hobbyDao; @Autowired
private UserDao userDao; @Autowired
private PhotoDao photoDao; @Override
public void destroy() throws Exception {
executor.shutdownNow();
} @Override
public void afterPropertiesSet() throws Exception { executor = new ScheduledThreadPoolExecutor(CORE_SIZE, new NamedThreadFactory("static-info-loader"));
RefreshCache refreshCache = new RefreshCache();
refreshCache.run();
executor.scheduleWithFixedDelay(refreshCache, cacheExpire, cacheExpire, TimeUnit.SECONDS); } private class RefreshCache implements Runnable {
@Override
public void run() {
log.info("---开始刷新角色权限缓存-----");
List<Role> roles = rolePermissionDao.getAllRole();
if (CollectionUtils.isNotEmpty(roles)) {
for (Role role : roles) {
List<Permission> permissions = rolePermissionDao.getPermissionByRole(role.getRid());
role.setPermissions(permissions);
redisCache.opsForValue().set(Constant.ROLE + role.getRid(), JSON.toJSONString(role));
}
} log.info("---开始刷新城市缓存-----");
List<City> cityProvince = cityDao.getAllProvince();
redisCache.opsForValue().set(Constant.CITY_ROOT, JSON.toJSONString(cityProvince));
if (CollectionUtils.isNotEmpty(cityProvince)) {
for (City sheng : cityProvince) {
List<City> shis = cityDao.getCityByParentId(sheng.getCid());
sheng.setChildren(shis);
redisCache.opsForValue().set(Constant.CITY + sheng.getCid(), JSON.toJSONString(sheng));
if (CollectionUtils.isNotEmpty(shis)) {
for (City shi : shis) {
List<City> xians = cityDao.getCityByParentId(shi.getCid());
shi.setChildren(xians);
redisCache.opsForValue().set(Constant.CITY + shi.getCid(), JSON.toJSONString(shi));
for (City xian : xians) {
redisCache.opsForValue().set(Constant.CITY + xian.getCid(), JSON.toJSONString(xian));
}
}
}
}
} log.info("---开始刷新兴趣爱好缓存-----");
List<HobbyType> allHobby = hobbyDao.getAllHobbys();
if(CollectionUtils.isNotEmpty(allHobby)){
for(HobbyType ht : allHobby){
List<Hobby> hobbys = hobbyDao.getHobbyItems(ht.getHtId());
if(CollectionUtils.isNotEmpty(hobbys)){
ht.setHobbys(hobbys);
}
redisCache.opsForValue().set(Constant.HOBBY + ht.getHtId(), JSON.toJSONString(ht));
}
} log.info("---开始刷新用户信息缓存-----");
List<UserInfo> userinfos = userDao.getAllUserInfo();
if(CollectionUtils.isNotEmpty(userinfos)){
for(UserInfo userInfo : userinfos){
List<Photos> photos = photoDao.getUserPhotos(userInfo.getUserId());
if(CollectionUtils.isNotEmpty(photos)){
userInfo.setPhotos(photos);
}
redisCache.opsForValue().set(Constant.USER_INFO + userInfo.getUserId(), JSON.toJSONString(userInfo));
}
} }
}
}

4.从redis中获取并解析为对象

@Override
public List<UserInfo> getUserInfoFromCache(int number) {
Set<String> sets = redis.keys(Constant.USER_INFO + "*");
Iterator<String> it = sets.iterator();
List<UserInfo> result = new LinkedList<UserInfo>();
int i = 0;
while(it.hasNext() && i<number){
String item = it.next();
String value = redis.opsForValue().get(item);
result.add(JSON.parseObject(value,UserInfo.class));
i++;
}
return result;
}

redis集成到Springmvc中及使用实例的更多相关文章

  1. Redis在Laravel项目中的应用实例详解

    https://mp.weixin.qq.com/s/axIgNPZLJDh9VFGVk7oYYA 在初步了解Redis在Laravel中的应用 那么我们试想这样的一个应用场景 一个文章或者帖子的浏览 ...

  2. 如何在springMVC 中对REST服务使用mockmvc 做测试

    如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试  spring 集成测试中对mock 的集成实在是太棒了!但 ...

  3. 【主流技术】Redis 在 Spring 框架中的实践

    前言 在Java Spring 项目中,数据与远程数据库的频繁交互对服务器的内存消耗比较大,而 Redis 的特性可以有效解决这样的问题. Redis 的几个特性: Redis 以内存作为数据存储介质 ...

  4. SpringMVC中使用Cron表达式的定时器

    SpringMVC中使用Cron表达式的定时器 cron(定时策略)简要说明 顺序: 秒 分 时 日 月 星期 年份 (7个参数,空格隔开各个参数,年份非必须参数) 通配符: , 如果分钟位置为* 1 ...

  5. Spring+Mybatis+SpringMVC+Maven+MySql搭建实例

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+M ...

  6. springmvc中request的线程安全问题

    SpringMvc学习心得(四)springmvc中request的线程安全问题 标签: springspring mvc框架线程安全 2016-03-19 11:25 611人阅读 评论(1) 收藏 ...

  7. 详解SpringMVC中Controller的方法中参数的工作原理[附带源码分析]

    目录 前言 现象 源码分析 HandlerMethodArgumentResolver与HandlerMethodReturnValueHandler接口介绍 HandlerMethodArgumen ...

  8. SpringMvc中Interceptor拦截器用法

    SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆等. 一. 使用场景 1 ...

  9. [Python][flask][flask-wtf]关于flask-wtf中API使用实例教程

    简介:简单的集成flask,WTForms,包括跨站请求伪造(CSRF),文件上传和验证码. 一.安装(Install) 此文仍然是Windows操作系统下的教程,但是和linux操作系统下的运行环境 ...

随机推荐

  1. Angular企业级开发(4)-ngResource和REST介绍

    一.RESTful介绍 RESTful维基百科 REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来 ...

  2. C#异步编程(二)

    async和await结构 序 前篇博客异步编程系列(一) 已经介绍了何谓异步编程,这篇主要介绍怎么实现异步编程,主要通过C#5.0引入的async/await来实现. BeginInvoke和End ...

  3. 如何安全的将VMware vCenter Server使用的SQL Server Express数据库平滑升级到完整版

    背景: 由于建设初期使用的vSphere vCenter for Windows版,其中安装自动化过程中会使用SQL Server Express的免费版数据库进行基础环境构建.而此时随着业务量的增加 ...

  4. JS继承之借用构造函数继承和组合继承

    根据少一点套路,多一点真诚这个原则,继续学习. 借用构造函数继承 在解决原型中包含引用类型值所带来问题的过程中,开发人员开始使用一种叫做借用构造函数(constructor stealing)的技术( ...

  5. ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案

    好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下: 出现乱码的原因: ...

  6. SAP CRM 将组件整合至导航栏中

    到现在,我们已经可以让组件独立地显示.我们只是运行它.让它显示在Web UI中.让我们把组件整合进导航栏,使我们可以在正常登录Web UI时访问它. 步骤一: 为你的UI组件主窗体创建一个内向插件. ...

  7. Android中的多线程断点下载

    首先来看一下多线程下载的原理.多线程下载就是将同一个网络上的原始文件根据线程个数分成均等份,然后每个单独的线程下载对应的一部分,然后再将下载好的文件按照原始文件的顺序"拼接"起来就 ...

  8. 【初码干货】使用阿里云对Web开发中的资源文件进行CDN加速的深入研究和实践

    提示:阅读本文需提前了解的相关知识 1.阿里云(https://www.aliyun.com) 2.阿里云CDN(https://www.aliyun.com/product/cdn) 3.阿里云OS ...

  9. php安装threads多线程扩展

    php5.3或以上,且为线程安全版本.apache和php使用的编译器必须一致.通过phpinfo()查看Thread Safety为enabled则为线程安全版.通过phpinfo()查看Compi ...

  10. 【微信SEO】公众号也能做排名?

    [写于2016年8月] 最近,微信团队发出一则公告,开放公众号运营者一年内更改公众号名一次,这对不少名字起的奇葩名字(包括dkplus)的公众号来说是一件好事. 为什么说是好事呢?公众号名字直接关联到 ...