SpringBoot2.0集成Redis的日常使用

前言:在SSM中往往整合一个redis都需要一堆配置,但是自从用了SpringBoot后这一堆配置就由框架来给我们做了,另外还给我们封装了常用的方法,下面我们来讲讲SpringBoot2.0中集成Redis,因为2.0和以前的版本有点不同,所以我们细细讲解。

第一步:直接导入Redis的依赖



    4.0.0

    com.itpengwei.idea.job
    springboot-job
    0.0.1-SNAPSHOT
    jar

    springboot-job
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            
            
            
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



第二步:为了能够使Redis可以直接存java对象,所以我们需要对其配置,以及自定义序列化器和反序列化器

package com.itpengwei.idea.job.springbootjob.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @author 彭伟
 * @date 2018/8/28 9:31
 */
public class RedisConverter implements RedisSerializer {
    private Converter serializer = new SerializingConverter();//序列化器
    private Converter deserializer = new DeserializingConverter();//反序列化器

    @Override
    public byte[] serialize(Object o) throws SerializationException {//将对象序列化成字节数组
        if (o == null) return new byte[0];
        try {
            return serializer.convert(o);
        } catch (Exception e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {//将字节数组反序列化成对象
        if (bytes == null || bytes.length == 0) return null;
        try {
            return deserializer.convert(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
 
  

第三步:将我们自定义的序列化器配置进操作Bean中

package com.itpengwei.idea.job.springbootjob.config;

import com.itpengwei.idea.job.springbootjob.utils.RedisConverter;
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;

/**
 * @author 彭伟
 * @date 2018/8/28 9:42
 * redis配置
 */
@Configuration
public class RedisConfig {


    /**
     * @param redisConnectionFactory
     * @return 自定义redisTemplate,自带的bean没有序列化器
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());//设置key的序列化器
        redisTemplate.setValueSerializer(new RedisConverter());//设置值的序列化器
        return redisTemplate;
    }
}

至于为什么我们需要自己重新来定义呢?接下来请看这么一段源码就知道了

SpringBoot2.0集成Redis的日常使用_第1张图片

第四步:可以开始进行测试增删改查了

package com.itpengwei.idea.job.springbootjob.controller;

import com.itpengwei.idea.job.springbootjob.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 彭伟
 * @date 2018/8/28 9:47
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    private String testString = "testString";
    private String userKey = "userKey";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/add")
    public String add() {
        //1,添加一个Value为String
        stringRedisTemplate.opsForValue().set(testString, "测试存储字符串类型");
        //2,添加一个Value为对象
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPassword("1111");
        user.setRediskey(userKey);
        redisTemplate.opsForValue().set(user.getRediskey(), user);
        return "成功";
    }

    @GetMapping("/getUser")
    public User findUserByKey() {
        User user = (User) redisTemplate.opsForValue().get(userKey);
        return user;
    }

    @GetMapping("/getString")
    public String findString() {
        String s = stringRedisTemplate.opsForValue().get(testString);
        return s;
    }
    @GetMapping("/delete")
    public String deleteByKey(){
        //1,删除string类型
        stringRedisTemplate.delete(testString);
        //2,删除user对象
        redisTemplate.delete(userKey);
        return "删除成功";
    }
}

最后请看下配置吧:差点忘记把配置贴上来了

SpringBoot2.0集成Redis的日常使用_第2张图片

请看小编的测试结果吧:

测试add:

SpringBoot2.0集成Redis的日常使用_第3张图片

测试查询:

SpringBoot2.0集成Redis的日常使用_第4张图片

测试删除:

SpringBoot2.0集成Redis的日常使用_第5张图片

 

你可能感兴趣的:(springboot,redis)