Springboot2.0集成Redis

2018-07-26  本文已影响220人  小宋_ed76

基于springboot2.0集成redis
step1、依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--springboot2.0集成redis需要这个依赖-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!--加入这个是为了让写入到redis中的数据已json的格式显示,看着爽不是罒ω罒-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.36</version>
        </dependency>
    </dependencies>

step2、redisconfig配置以及使用fastjson实现序列号

package com.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @author: songgt
 * @date: 2018-07-11 8:52
 */
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

step3、fastjson序列化处理

package com.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
/**
 * @author: songgt
 * @date: 2018-07-11 8:52
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class<T> clazz;
    public FastJsonRedisSerializer(Class<T> clazz){
        super();
        this.clazz = clazz;
    }
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t){
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <=0){
            return null;
        }
        String str = new String(bytes,DEFAULT_CHARSET);
        //这里解决一个问题:如果有多个包,就写多个addAccept
        //解决com.alibaba.fastjson.JSONException: autoType is not support
        ParserConfig.getGlobalInstance().addAccept("com.entity.CatProduct");
        return JSON.parseObject(str,clazz);
    }
}

step4、service层实现对list的操作

package com.service.impl;

import com.entity.CatProduct;
import com.service.CatService;
import org.assertj.core.util.Lists;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
 * @author: songgt
 * @date: 2018-07-11 8:52
 */
@Service("catServiceImpl")
public class CatServiceImpl implements CatService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public Long addProduct(CatProduct catProduct) {
        List<CatProduct> catProductList = Lists.newArrayList();
        catProductList.add(catProduct);
        long x = redisTemplate.opsForList().leftPush(catProduct.getUserId()+catProduct.getPId()+"",catProductList);
        return x;
    }
    @Override
    public List<CatProduct> getProductFromCat() {
        //这里的redisTemplate.opsForList().leftPop("10127")取出数据后会删除掉这个key
        List<CatProduct> catProductList = (List<CatProduct>) redisTemplate.opsForList().leftPop("10127");
        return catProductList;
    }
}

以上便是整合redis的过程,省略了CatProduct(购物车)和CatService接口
----仅此作为记录,方便后续工作中对redis的快速集成使用,如果您看了这篇文章,有更好的意见欢迎您的指正

上一篇下一篇

猜你喜欢

热点阅读