spring-data整合redis

作者: 编程界的小学生 | 来源:发表于2017-03-09 14:06 被阅读177次

    1、jar包

       <dependencies>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.8.1.RELEASE</version>
            </dependency>
        </dependencies>
    

    2、redis.properties

    redis.host=127.0.0.1
    redis.port=6379
    redis.pass=
      
    redis.database=1
      
    redis.maxIdle=200
    redis.maxTotal=200
    redis.testOnBorrow=true
    

    3、spring-data-redis.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:p="http://www.springframework.org/schema/p"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
        xmlns:aop="http://www.springframework.org/schema/aop"  
        xsi:schemaLocation="  
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
      
        <context:property-placeholder location="classpath:redis.properties" />  
        
        <context:component-scan base-package="redis.base" />
    
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
            <property name="maxTotal" value="${redis.maxTotal}"/>
            <property name="maxIdle" value="${redis.maxIdle}"/>
            <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        </bean>  
        
        <!-- Jedis ConnectionFactory 数据库连接配置-->
        <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <property name="hostName" value="${redis.host}"/>
            <property name="port" value="${redis.port}"/>
            <property name="password" value="${redis.pass}"/>
            <property name="poolConfig" ref="jedisPoolConfig"/>
            <property name="database" value="${redis.database}"/>
        </bean>
        
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="jedisConnectionFactory" />
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
        </bean>
          
    </beans>
    

    4、接口类

    package redis.base;
    
    /**
     * redis基础操作接口
     * @author 15620646321@163.com
     * @date 2017年3月9日
     */
    public interface IRedisBasicDAO {
    
        /**
         * 写入一个字符串
         * 
         * @param keyPrefix 前缀
         * @param keySuffix 后缀
         * @param value     值
         * @throws Exception
         */
        void setString(String keyPrefix, String keySuffix, String value) throws Exception;
        
        /**
         * 获取一个字符串
         * 
         * @param keyPrefix 前缀
         * @param keySuffix 后缀
         * @return          值
         * @throws Exception
         */
        String getString(String keyPrefix, String keySuffix) throws Exception;
    }
    

    5、接口实现类

    package redis.base;
    
    import java.io.Serializable;
    
    import javax.annotation.Resource;
    
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Repository;
    import org.springframework.util.StringUtils;
    
    /**
     * BasicImpl
     * @author 15620646321@163.com
     * @date 2017年3月9日
     */
    @Repository
    public class RedisBasicDAO implements IRedisBasicDAO {
        
        @Resource
        private RedisTemplate<Serializable, Serializable> redisTemplate;
        
        @Override
        public void setString(String keyPrefix, String keySuffix, String value)
                throws Exception {
            
            if(null == keyPrefix || null == keySuffix || null == value) {
                return ;
            }
    //      获得key
            String key = keyPrefix + keySuffix;
            if(StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
                return ;
            }
    //      写入redis
            /*redisTemplate.execute((RedisCallback) redisConnection -> {
                redisConnection.set(redisTemplate.getStringSerializer().serialize(key), 
                        redisTemplate.getStringSerializer().serialize(value));
                return null;
            });*/
            redisTemplate.execute(new RedisCallback<Serializable>() {
    
                @Override
                public Serializable doInRedis(RedisConnection connection)
                        throws DataAccessException {
                    connection.set(redisTemplate.getStringSerializer().serialize(key), redisTemplate.getStringSerializer().serialize(value));
                    return null;
                }
            });
        }
    
        @Override
        public String getString(String keyPrefix, String keySuffix)
                throws Exception {
            
            if(null == keyPrefix || null == keySuffix) {
                return null;
            }
    //      获得key
            String key = keyPrefix + keySuffix;
            if(StringUtils.isEmpty(key)) {
                return null;
            }
            byte[] value;
            value = (byte[]) redisTemplate.execute((RedisCallback<Serializable>) redisConnection -> redisConnection.get(
                    redisTemplate.getStringSerializer().serialize(key)));
            return (String) redisTemplate.getStringSerializer().deserialize(value);
        }
    
    }
    

    6、测试类

    package redis.util;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import redis.base.RedisBasicDAO;
    
    /**
     * 测试类
     * @author 15620646321@163.com
     * @date 2017年3月8日
     */
    public class RedisTest {
        public static void main(String[] args) throws Exception {
            ApplicationContext context =  new ClassPathXmlApplicationContext("classpath:spring/spring-data-redis.xml");
            RedisBasicDAO redisBasicDAO = (RedisBasicDAO)context.getBean("redisBasicDAO");
            redisBasicDAO.setString("null", "pointer", "NullPointerException");
            System.out.println(redisBasicDAO.getString("null", "pointer"));
        }
    }
    

    若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
    欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:


    qrcode_for_gh_577b64e73701_258.jpg

    相关文章

      网友评论

        本文标题:spring-data整合redis

        本文链接:https://www.haomeiwen.com/subject/utbwgttx.html