SpringMVC + Spring-data-redis整合完整示例

最近在学习Spring-data-redis,现在搭建了一个完整的示例,分享给大家作为参考,废话不多说,直接上源码

首先导入必要的jar包

如图选中项

然后添加SpringMVC + Redis的配置文件

配置文件

在src目录下,新建一个config文件夹,文件夹中包含5个配置文件,log4j.propertiesredis.propertiesredis-context.xmlspring-context.xmlspring-mvc.xml

log4j.properties

log4j.rootLogger=info, console, info, error

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[youcl][%x] %-4d{HH\:mm\:ss} %-5p %c[%L] - %m%n

log4j.appender.info.encoding=UTF-8
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.Append=true
log4j.appender.info.Threshold = INFO 
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.DatePattern='.'yyyy-MM-dd
log4j.appender.info.layout.ConversionPattern=[youcl][%x] %-4d{HH\:mm\:ss} %-5p %c[%L] - %m%n
log4j.appender.info.File=${webapp.root}/WEB-INF/logs/info.log

log4j.appender.error.encoding=UTF-8
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.Append=true
log4j.appender.error.Threshold = ERROR 
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=[youcl][%x] %-4d{HH\:mm\:ss} %-5p %c[%L] - %m%n
log4j.appender.error.File=${webapp.root}/WEB-INF/logs/error.log

redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.pass=youcl.com_redis

redis.maxIdle=200
redis.maxTotal=512
redis.maxWaitMillis=3000
redis.testOnBorrow=true

redis-context.xml

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

    <!-- 扫描redis.properties文件-->
    <context:property-placeholder location="classpath:config/redis.properties" />

    <!-- 读取redis开始 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}" />         <!--最大分配的对象数 -->
        <property name="maxIdle" value="${redis.maxIdle}" />               <!--最大能够保持idel空闲状态的对象数 -->
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> <!--最大等待时间ms -->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />   <!-- 当调用borrow Object方法时,在获取连接的时候是否进行检查有效性 -->
    </bean>

    <!-- redis连接工厂类 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
        p:pool-config-ref="jedisPoolConfig" />
    
    <!-- redis模板类 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnectionFactory" />

</beans>


spring-context.xml

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

    <context:annotation-config/>
    <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 -->
    <context:component-scan base-package="com.youcl.wechat.*" />
  
    <!-- 启用spring mvc 注解 -->
    <mvc:annotation-driven />
    
    <!-- 引入同文件夹下的redis属性配置文件 -->
    <import resource="redis-context.xml"/>

</beans>



spring-mvc.xml

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

    <!-- 配置视图解析器,把控制器的逻辑视图映射为真正的视图 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
    
</beans>

web.xml配置

<?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>youcl</display-name>
  
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <!--  **************   Log4j 配置  ********   -->
     <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root</param-value>
     </context-param>
     <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:config/log4j.properties</param-value>
     </context-param>
     <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
     </listener>
    <!--  *************   Log4j 配置End  *******   -->
    
    
    <!--  *************************************   Spring & Spring MVC 配置  *************************************   -->
    <!-- 启用Spring监听 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 加载spring相关的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/spring-context.xml</param-value>
    </context-param>

    <!-- 加载SpringMVC配置 start -->
    <servlet>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- SpringMVC配置end -->
    <!--  *************************************   Spring & Spring MVC 配置End  ********************************   -->
    
</web-app>

Java代码

Member.java

import java.io.Serializable;

public class Member implements Serializable{
    private static final long serialVersionUID = -5319282235052357051L;
    
    private String id;
    private String nickname;

    public Member() {
    }

    public Member(String id, String nickname) {
        this.setId(id);
        this.setNickname(nickname);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }   
}

RedisGeneratorDao.java

import java.io.Serializable;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis工具Dao
 * @author X-rapido
 *
 * @param <K>
 * @param <V>
 */
public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable> {

    @Resource
    protected RedisTemplate<K, V> redisTemplate;

    /**
     * 获取 RedisSerializer <br>
     */
    protected RedisSerializer<String> getStringSerializer() {
        return redisTemplate.getStringSerializer();
    }

}

MemberDao.java

import java.util.List;
/**
 * 会员Dao层接口
 * @author X-rapido
 */
public interface MemberDao {
    
    /**
     * 添加会员
     * @param member
     * @return
     */
    boolean add(Member member);

    /**
     * 添加会员集合
     * @param list
     * @return
     */
    abstract boolean add(List<Member> list);

    /**
     * 删除
     * @param key
     */
    void delete(String key);

    /**
     * 获取
     * @param keyId
     * @return
     */
    Member get(String keyId);
}

MemberDaoImpl.java

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.youcl.wechat.redis.dao.RedisGeneratorDao;

@Repository(value = "memberDao")
public class MemberDaoImpl extends RedisGeneratorDao<String, Member> implements MemberDao {

    /**
     * 添加对象
     */
    @Override
    public boolean add(final Member member) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key =  getStringSerializer().serialize(member.getId());
                byte[] name =  getStringSerializer().serialize(member.getNickname());
                return connection.setNX(key, name);
            }
        });
        return result;
    }

    /**
     * 添加集合
     */
    @Override
    public boolean add(final List<Member> list) {
        Assert.notEmpty(list);
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                for (Member member : list) {
                    byte[] key =  getStringSerializer().serialize(member.getId());
                    byte[] name =  getStringSerializer().serialize(member.getNickname());
                    connection.setNX(key, name);
                }
                return true;
            }
        }, false, true);
        return result;
    }

    /**
     * 删除对象 ,依赖key
     */
    @Override
    public void delete(String key) {
        List<String> list = new ArrayList<String>();
        list.add(key);
        delete(list);
    }

    /**
     * 删除集合 ,依赖key集合
     */
    public void delete(List<String> keys) {
        redisTemplate.delete(keys);
    }

    /**
     * 根据key获取对象
     */
    @Override
    public Member get(final String keyId) {
        Member result = redisTemplate.execute(new RedisCallback<Member>() {
            public Member doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key =  getStringSerializer().serialize(keyId);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String nickname =  getStringSerializer().deserialize(value);
                    return new Member(keyId, nickname);
                }
                return null;
            }
        });
        return result;
    }

}

MemberService.java

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

/**
 * 会员Service层
 * @author Administrator
 *
 */
@Service(value="memberService")
public class MemberService {
    
    @Resource(name = "memberDao")
    private MemberDao memberDao;

    public void add(Member member) {
        memberDao.add(member);
    }
    
    public void add(List<Member> memberList) {
        memberDao.add(memberList);
    }

    public void delete(String id) {
        memberDao.delete(id);
    }

    public Member get(String id) {
        return memberDao.get(id);
    }
}

MemberController.java

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/member")
public class MemberController {
    private static final Logger logger = Logger.getLogger(MemberController.class);

    @Resource
    private MemberService memberService;

    /**
     * 添加单个对象
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = { "/add"})
    public String add(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        Member member = new Member();
        member.setId("123");
        member.setNickname("优客志 - http://www.youcl.com");
        memberService.add(member);
        
        modelMap.addAttribute(member);
        
        logger.info("添加单个对象成功");
        return "redisTest";
    }
    
    /**
     * 添加集合对象
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = { "/addList"})
    public String addList(ModelMap modelMap) {
        List<Member> memberList = new ArrayList<Member>();
        Member member_1 = new Member("id_1","name_1");
        Member member_2 = new Member("id_2","name_2");
        Member member_3 = new Member("id_3","name_3");
        memberList.add(member_1);
        memberList.add(member_2);
        memberList.add(member_3);
        memberService.add(memberList);  // 添加集合
        modelMap.addAttribute("memberList",memberList);
        
        logger.info("添加集合对象成功");
        return "redisTest";
    }
    
    /**
     * 查询
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(value = { "/{id:\\d+}/query"})
    public String query(@PathVariable("id") String id, ModelMap modelMap) {
        Member member = memberService.get(id);
        if (null != member) {
            modelMap.addAttribute("message", "查询Id=" + id + "的用户名为:" + member.getNickname());
        } else {
            modelMap.addAttribute("message", "没有查询到与Id=" + id + "相关的数据");
        }
        
        logger.info("查询对象成功");
        return "redisTest";
    }

    /**
     * 删除
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(value = { "/{id:\\d+}/delete"})
    public String delete(@PathVariable("id") String id, ModelMap modelMap) {
        try {
            memberService.delete(id);
            modelMap.addAttribute("message", "删除Id为" + id + "的用户成功.");
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute("message", "删除Id为" + id + "的用户失败, " + e.getMessage());
        }

        logger.info("删除对象成功");
        return "redisTest";
    }
}

JSP页面跳转

在WEB-INF下新建一个jsp文件夹,在里面新建一个redisTest.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Redis测试</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
  </head>
  
  <body>
      <center>
          <p>
            测试添加Redis值:${member.id},${member.nickname}
          </p>
          <br>
          <br>
          --------------------------------------------------
          <p>
            测试添加Redis集合值:
            <c:forEach items="${memberList }" var="mem">
                ${mem.id},${mem.nickname}
            </c:forEach>
          </p>
          <br>
          <br>
          --------------------------------------------------
          <p>
            测试查询Redis值:${message}
          </p>
          <br>
          <br>
          <p>
            测试删除Redis值:${message}
          </p>
      </center>
  </body>
</html>

测试运行

[youcl][] 15:14:11 INFO  com.youcl.wechat.redis.demo.MemberController[40] - 添加单个对象成功
[youcl][] 15:17:37 INFO  com.youcl.wechat.redis.demo.MemberController[63] - 添加集合对象成功
[youcl][] 15:18:14 INFO  com.youcl.wechat.redis.demo.MemberController[82] - 查询对象成功
[youcl][] 15:18:53 INFO  com.youcl.wechat.redis.demo.MemberController[102] - 删除对象成功
[youcl][] 15:19:27 INFO  com.youcl.wechat.redis.demo.MemberController[82] - 查询对象成功

优化基类,使用RedisBaseDao方式,请看下一篇文章

SpringMVC + Spring-data-redis整合完整示例(续)

有关connection.set方法如下图,具体意思,参考以后的文章更新吧,请持续关注文章更新,慢慢积累学习


赞(52) 打赏
未经允许不得转载:优客志 » JAVA开发
分享到:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏