1. 程式人生 > >SpringBoot整合Redis

SpringBoot整合Redis

結構 dep 實體類 final [] serialize value keys test

結構:

技術分享圖片

pom引入依賴:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <
artifactId>fastjson</artifactId> <version>1.2.8</version> </dependency>

application.yml配置:

spring:
  redis:
    host: 192.168.3.101
    port: 6379
    password: redis-01

Order實體類:

package com.example.bootredis;

public class Order {
    private Integer orderId;
    
private String orderName; public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) {
this.orderName = orderName; } }

redis序列化器(默認的jackson)(代碼中已經註釋掉了)

使用fastjson需要自定義序列化器:

package com.example.bootredis.serializer;

import com.alibaba.fastjson.JSON;
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;

/**
 * 自定義序列化類
 * @param <T>
 */
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);
        return (T) JSON.parseObject(str, clazz);
    }

}

裝配序列化器

package com.example.bootredis.config;

import com.example.bootredis.serializer.FastJsonRedisSerializer;
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;

@Configuration
public class RedisConfiguration {

    /*@Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(connectionFactory);
        // 使用jackson2的序列對象
        RedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setDefaultSerializer(genericJackson2JsonRedisSerializer);

        return redisTemplate;
    }*/

    @Bean
    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;
    }
}

測試類:

package com.example.bootredis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

@SpringBootApplication
public class BootRedisApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext
                context = SpringApplication.run(BootRedisApplication.class, args);
        Map<String, RedisTemplate> beansOfType = context.getBeansOfType(RedisTemplate.class);
        System.out.println(beansOfType);
        System.out.println("-----------------");
        RedisTemplate redisTemplate = context.getBean("stringRedisTemplate", RedisTemplate.class);
        redisTemplate.opsForValue().set("test", "test-value");
        Order order = new Order();
        order.setOrderId(100001);
        order.setOrderName("商品訂單");
        // redisTemplate.opsForValue().set("order", JSON.toJSONString(order));
        // 通過配置jackson的序列化器操作的
        /*RedisTemplate cRedisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
        //cRedisTemplate.opsForValue().set("order-1", order);
        System.out.println(cRedisTemplate.opsForValue().get("order-1"));*/
        RedisTemplate cRedisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
        cRedisTemplate.opsForValue().set("order-1", order);

        context.close();
    }
}

 

SpringBoot整合Redis