redis最佳实践

总结:

String类型的value(string/list/set/hash)使用StringRedisTemplate

其他类型的value(string/list/set/hash/object)使用RedisTemplate(GenericFastJsonRedisSerializer,value都会序列化为json)

 

value为string时,

如果使用RedisTemplate(使用GenericFastJsonRedisSerializer序列化)时,value值 带双引号。即:"遥远2"。

如果使用StringRedisTemplate,value值不带双引号。即:遥远2

 

 

1、pom


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
</parent>


<
dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.41</version> </dependency> </dependencies>

 

2、application-dev.yml

spring:
  redis:
    host: 10.134.253.30
    port: 6379
    password: 123456
    # 连接超时时间:ms
    timeout: 5000
    pool:
      # 连接池最大连接数(使用负值表示没有限制)
      max-active: 8
      # 连接池最大阻塞等待时间(使用负值表示没有限制)
      max-wait: -1
      # 连接池中的最大空闲连接
      max-idle: 8
      # 连接池中的最小空闲连接
      min-idle: 0
      

3、RedisConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;

@Configuration
public class RedisConfig {
    
    @Bean("jsonRedisTemplate")
    public RedisTemplate<Object,Object> jsonRedisTemplate(RedisConnectionFactory redisConectionFactory) {
        RedisTemplate<Object,Object> template = new RedisTemplate<Object,Object>();
        template.setConnectionFactory(redisConectionFactory);
        
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericFastJsonRedisSerializer());
        //hash
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

 

4、测试类

4.1、StringRedisTemplateTest

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class StringRedisTemplateTest {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Test
    public void testValue() throws Exception {
        stringRedisTemplate.opsForValue().set("zuo:1", "遥远2");
        String val = stringRedisTemplate.opsForValue().get("zuo:1");
        log.info("值={}",val);
    }
    @Test
    public void testList() throws Exception {
        stringRedisTemplate.opsForList().leftPush("list:zuo", "左");
        stringRedisTemplate.opsForList().leftPush("list:zuo", "杨");
        stringRedisTemplate.opsForList().leftPush("list:zuo", "王");
        
        long len = stringRedisTemplate.opsForList().size("list:zuo");
        for (int i = 0; i < len; i++) {
            String val = stringRedisTemplate.opsForList().leftPop("list:zuo");//先进后出
            /*
             * 0:王
             * 1:杨
             * 2:左
             */
            log.info("{}:{}",i,val);
        }
    }
    @Test
    public void testHash() throws Exception {
        stringRedisTemplate.opsForHash().put("hash:zuo", "name", "遥远2");;
        stringRedisTemplate.opsForHash().put("hash:zuo", "age", "18");
        String age = (String)stringRedisTemplate.opsForHash().get("hash:zuo", "age");
        log.info("{}",age);
    }
    @Test
    public void testSet() throws Exception {
        stringRedisTemplate.opsForSet().add("set:zuo", "1");
        stringRedisTemplate.opsForSet().add("set:zuo", "2");
        stringRedisTemplate.opsForSet().add("set:zuo", "3");
        long len = stringRedisTemplate.opsForSet().size("set:zuo");
        for (int i = 0; i < len; i++) {
            String s = stringRedisTemplate.opsForSet().pop("set:zuo");
            log.info("{}",s);
        }
    }
    @Test
    public void testBound() throws Exception {
        BoundListOperations operations = stringRedisTemplate.boundListOps("list:zuo");
        operations.leftPush("左");
        operations.leftPush("杨");
        operations.leftPush("王");
        
        List<String> list = operations.range(0, operations.size());
        list.stream().forEach(s -> System.out.println(s));
    }

}

4.2、RedisTemplateTest

import lombok.extern.slf4j.Slf4j;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import com.ebc.entity.User;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class RedisTemplateTest {
    @Autowired
    private RedisTemplate<Object,Object> jsonRedisTemplate;//不能为RedisTemplate<K,V>
    @Test
    public void testHash() throws Exception {
        String key = "redistemplate:hash";
        jsonRedisTemplate.opsForHash().put(key, "name", "遥远2");
        jsonRedisTemplate.opsForHash().put(key, "age", 18);
        int age = (Integer)jsonRedisTemplate.opsForHash().get(key, "age");
        log.info("{}", age);
    }
    @Test
    public void testObj() throws Exception {
        String key = "redistemplate:user";
        jsonRedisTemplate.delete(key);
        jsonRedisTemplate.opsForValue().set(key, User.getSampleUser());
        
        User user = (User)jsonRedisTemplate.opsForValue().get(key);
        log.info("{}", user);
    }
    
}

4.3、RedisTemplateTest2

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class RedisTemplateTest2 {

    @Autowired()
    private RedisTemplate<Object,Object> jsonRedisTemplate;
    
    @Test
    public void testValue() throws Exception {
        jsonRedisTemplate.opsForValue().set("redistemplate:value:int", 1);
        jsonRedisTemplate.opsForValue().set("redistemplate:value:long", 1L);
        jsonRedisTemplate.opsForValue().set("redistemplate:value:double", 1d);
        
        int i = (int)jsonRedisTemplate.opsForValue().get("redistemplate:value:int");
        long l = (long)jsonRedisTemplate.opsForValue().get("redistemplate:value:long");
        double d = (double)jsonRedisTemplate.opsForValue().get("redistemplate:value:double");
        
        log.info("{},{},{}",i,l,d);
    }
    @Test
    public void testList() throws Exception {
        String key = "redistemplate:list";
        jsonRedisTemplate.opsForList().leftPush(key, 1);
        jsonRedisTemplate.opsForList().leftPush(key, 2);
        jsonRedisTemplate.opsForList().leftPush(key, 3);
        
        long len = jsonRedisTemplate.opsForList().size(key);
        for (int i = 0; i < len; i++) {
            int val = (int)jsonRedisTemplate.opsForList().leftPop(key);//先进后出
            /*
             * 0:3
             * 1:2
             * 2:1
             */
            log.info("{}:{}",i,val);
        }
    }
    @Test
    public void testSet() throws Exception {
        String key = "redistemplate:set";
        jsonRedisTemplate.opsForSet().add(key, 1);
        jsonRedisTemplate.opsForSet().add(key, 2);
        jsonRedisTemplate.opsForSet().add(key, 3);
        long len = jsonRedisTemplate.opsForSet().size(key);
        for (int i = 0; i < len; i++) {
            int s = (int)jsonRedisTemplate.opsForSet().pop(key);
            log.info("{}",s);
        }
    }
    @Test
    public void testBound() throws Exception {
        BoundListOperations operations = jsonRedisTemplate.boundListOps("redistemplate:list");
        operations.leftPush(1);
        operations.leftPush(2);
        operations.leftPush(3);
        
        List<Integer> list = operations.range(0, operations.size());
        list.stream().forEach(s -> System.out.println(s));
    }

}

 

posted @ 2018-10-30 09:30  遥远2  阅读(577)  评论(0编辑  收藏  举报