spring + redis + spring-data-redis2.0.10 整合-单机版

github源码下载  下载redis-stand-alone分支

 

1.添加pom依赖


    
        5.0.8.RELEASE
        2.9.0
    

    
        
            org.springframework
            spring-context
            ${spring.version}
        

        
            redis.clients
            jedis
            ${redis.version}
        

        
            org.springframework.data
            spring-data-redis
            2.0.10.RELEASE
        

        
            com.fasterxml.jackson.core
            jackson-databind
            2.8.10
         

        
            org.springframework
            spring-test
            ${spring.version}
        
        
        
            org.slf4j
            slf4j-log4j12
            1.7.25
        


        
            junit
            junit
            4.12
        

    

2.创建redis.propeties和 log4j.properties


redis.hostName=192.168.1.62
redis.port=6379
#超时时间 默认2000 如果使用pool技术 这个参数就毫无意义
redis.timeout=100000
defaultCacheExpireTime=60

#最大空闲数
redis.maxIdle=400
#最大空连接数
redis.maxTotal=5000
#最大等待时间
redis.maxWaitMillis=1000
#连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true
redis.blockWhenExhausted=true
#返回连接时,检测连接是否成功
redis.testOnBorrow = true
#定义LOG输出级别
log4j.rootLogger=INFO,Console  
#定义日志输出目的地为控制台
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=[%c] - %m%n  

3.创建RedisConfig和SpringBeanConfig的javaConfig类


 

package com.roger.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@PropertySource(value = "classpath:redis.properties")
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${redis.hostName}")
    private String hostName;
    @Value("${redis.port}")
    private int port;
    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.blockWhenExhausted}")
    private boolean blockWhenExhausted;
    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;

    @Autowired
    private JedisPoolConfig jedisPoolConfig;

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);

        return jedisPoolConfig;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(){

        RedisStandaloneConfiguration redisStandaloneConfig = new RedisStandaloneConfiguration();

        redisStandaloneConfig.setHostName(hostName);
        redisStandaloneConfig.setPort(port);

        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder
                jedisPoolConfigBuilder = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();

        jedisPoolConfigBuilder.poolConfig(jedisPoolConfig);

        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfig,jedisPoolConfigBuilder.build());
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate redisTemplate(){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        RedisSerializer stringRedisSerializer = new StringRedisSerializer();

        RedisTemplate redisTemplate = new RedisTemplate();

        redisTemplate.setConnectionFactory(jedisConnectionFactory);

        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;

    }

}
package com.roger.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.roger")
public class SpringBeanConfig {
}

4.创建RedisCacheManager类


 

package com.roger.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCacheManager {

    @Autowired
    private RedisTemplate redisTemplate;

    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    public boolean setNX(String key,Object value){
      return redisTemplate.opsForValue().setIfAbsent(key,value);
    }

    public long del(String... key){
        if(StringUtils.isEmpty(key))
            return 0;
       return redisTemplate.delete(CollectionUtils.arrayToList(key));
    }

    public boolean expire(String key,long time,TimeUnit timeUnit){
        return redisTemplate.expire(key,time,timeUnit);
    }
}

5.创建测试基类SpringBaseTestSuit 和 TestRedisCacheManager类


package com.roger;

import com.roger.config.RedisConfig;
import com.roger.config.SpringBeanConfig;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringBeanConfig.class,RedisConfig.class})
public class SpringBaseTestSuit {
}
package com.roger.manager;

import com.roger.SpringBaseTestSuit;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class TestRedisCacheManager extends SpringBaseTestSuit {

    @Autowired(required = false)
    private RedisCacheManager redisCacheManager;

    @Test
    public void testRedisCofig(){
        Assert.assertTrue(redisCacheManager != null);
    }

    @Test
    public void testGet(){
        Object name = redisCacheManager.get("name");
        Assert.assertNull(name);

        redisCacheManager.set("name","roger");
        name = redisCacheManager.get("name");
        Assert.assertNotNull(name);

        long delCount = redisCacheManager.del("name");
        Assert.assertTrue( delCount == 1);
    }

    @Test
    public void testSetNX(){
        boolean ifAbsent = redisCacheManager.setNX("name","roger");
        Assert.assertTrue(ifAbsent);

        ifAbsent = redisCacheManager.setNX("name","Mary");
        Assert.assertFalse(ifAbsent);

        Object name = redisCacheManager.get("name");
        Assert.assertTrue("roger".equals(name));

        long delCount = redisCacheManager.del("name");
        Assert.assertTrue(delCount == 1);

    }
}

 

你可能感兴趣的:(redis)