1. 程式人生 > >springBoot redis應用demo

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());
        }
    }
}

其他功能,請自行測試