springBoot redis应用demo

首先,模板配置

这里maven配置省略了,请自行添加dependency

其次,redis配置信息

# Redis数据库索引(默认为db0)
spring.redis.database=0
## 测试环境配置----Redis服务器地址
#spring.redis.host=192.168.0.153
## Redis服务器连接密码(默认为空)
#spring.redis.password=123456
## Redis服务器连接端口
#spring.redis.port=6379

# 本地环境配置---Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接密码(默认为空)
spring.redis.password=
# Redis服务器连接端口
spring.redis.port=6369

# pool settings ...
# 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
# 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
# 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
# 连接超时时间(毫秒)
#spring.redis.timeout=0

然后,序列化

package com.cyipp.skynet.oms.core;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisConfig
 * @Description 数据序列化,以下两种redisTemplate自由根据场景选择
 * @Author huoNan
 * @Time 2018/8/2 17:34
 * @Version 1.0
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    @SuppressWarnings("unchecked")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

测试demo

package com.cyipp.skynet.oms;

import com.cyipp.skynet.oms.web.Student;
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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTests {

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Test
    public void contextLoads() {
        System.out.println("hello world");
    }


    @Test
    public void testRedisSet() {
        Student student = new Student();
        student.setAge(18);
        student.setName("lee");
        student.setId(2);

        redisTemplate.opsForValue().set(student.getId() + "", student);
    }


    @Test
    public void testRedisGet() {
        Student stu = (Student) redisTemplate.opsForValue().get("2");
        System.out.println(stu.toString());
    }

    @Test
    public void testRedisExpire() {
        redisTemplate.expire("1", 15, TimeUnit.SECONDS);
    }

    @Test
    public void testRedisDelete() {
        redisTemplate.delete("2");
    }


    /**
     * 功能描述: increment(),当key存在时,value+,
     *                      当key不存在时,创建后,value+,
     *                      且increment()有效的处理了并发的问题
     * @date 2018/8/2 16:42
     */
    @Test
    public void testRedisIncrement() {
//        redisTemplate.opsForValue().set("1",1);
        redisTemplate.opsForValue().increment("2",2L);
    }


    /**
     * 功能描述: redis添加list对象
     * @date 2018/8/2 17:28
     */
    @Test
    @SuppressWarnings("unchecked")
    public void testRedisList_pust(){
        List list = new ArrayList();
        for (int i=0;i<5;i++){
            list.add("lee"+i);
        }
        redisTemplate.opsForList().rightPushAll("list",list);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testRedisList2_push(){
        List list = new ArrayList();
        for (int i=0;i<5;i++){
            Student student = new Student();
            student.setId(i);
            student.setName("lee"+i);
            student.setAge(18);
            list.add(student);
        }
        redisTemplate.opsForList().rightPushAll("list2",list);
    }


    /**
     * 功能描述: dang end=-1时,取所有数据
     * @date 2018/8/2 19:10
     */
    @Test
    public void testRedisList_range(){
        List<Object> list = redisTemplate.opsForList().range("list2", 0, 2);
        for (Object obj : list) {
            System.out.println(obj.toString());
        }
    }
}

其他功能,请自行测试

猜你喜欢

转载自blog.csdn.net/hacker_Lees/article/details/81367145