1.5、将spring-redis.xml包含到web.xml中
<servlet> <description></description> <display-name>DispatcherServlet</display-name> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description></description> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/spring-*.xml</param-value> --此处包含所有spring配置文件 </init-param> <load-on-startup>1</load-on-startup> </servlet>
1.6、在需要redis的业务类中注入redisUtil
此处用一个方法理解redis的使用:
/** * ArticleServiceImp.java */ package com.zzipsun.service.imp; import java.sql.Array; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.zzipsun.dao.ArticleDao; import com.zzipsun.entity.Article; import com.zzipsun.service.base.ArticleService; import com.zzipsun.util.Log4JUtil; import com.zzipsun.util.RedisUtil; /** * @author zs * */ @Service("articleService") public class ArticleServiceImp implements ArticleService { Logger log=Logger.getLogger(ArticleServiceImp.class); @Resource ArticleDao articleDao; @Value("#{jdbc.pagesize}") int pageSize; @Resource RedisUtil redisUtil; /* (non-Javadoc) * @see com.zzipsun.service.base.ArticleService#findArticleById(java.lang.String) */ //查看一个文章 public Article findArticleById(String articleId) { if(articleId.trim()==""||articleId==null) { throw new RuntimeException("您查看的文章找不到了"); } //尝试从redis缓冲中获取map中的article实体对象 Article article=(Article)redisUtil.hget("article", articleId); if(article!=null) { log.debug("redis中的id为"+articleId+"的article标题为"+article.getTitle()); } //如果redis缓存中不存在此文章 if(article==null) { //数据库查询 article=articleDao.findArticleById(articleId); //存入redis中 redisUtil.hset("article", articleId, article); } return article; } }