springboot+Redis 使用Hessian序列化

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.JavaSerializer;
import com.caucho.hessian.io.Serializer;
import com.caucho.hessian.io.SerializerFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Suppliers;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnel;
import com.google.common.hash.PrimitiveSink;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class bloom {

    private static RedisTemplate  stringRedisTemplate = Suppliers.memoize(
        () -> initRedis()).get();
    private static Serializer serializer = JavaSerializer.create(BloomFilter.class);

    private static RedisTemplate<String,String> initRedis(){
        FastJson2JsonRedisSerializer<Object> redisSerializer = new FastJson2JsonRedisSerializer<>(
            Object.class);
        SerializerFactory serializerFactory = new SerializerFactory(
            BloomFilter.class.getClassLoader());
        RedisStandaloneConfiguration poolConfig = new RedisStandaloneConfiguration();
        poolConfig.setDatabase(0);
        poolConfig.setHostName("120.1.1.1");
        poolConfig.setPassword(RedisPassword.of("密码"));
        poolConfig.setPort(6379);
        LettuceConnectionFactory factory = new LettuceConnectionFactory(poolConfig);
        factory.afterPropertiesSet();
        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisSerializer(){

            @Override
            public byte[] serialize(Object o) throws SerializationException {

                try {

                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
                    hessian2Output.setSerializerFactory(serializerFactory);

                    hessian2Output.startMessage();
                    hessian2Output.writeObject(o);
                    hessian2Output.completeMessage();
                    hessian2Output.close();
                    return byteArrayOutputStream.toByteArray();

                } catch (IOException e) {
                    log.warn("序列化异常");
                    throw new RuntimeException(e);
                }
            }

            @Override
            public Object deserialize(byte[] bytes) throws SerializationException {

                Hessian2Input hessian2Input = new Hessian2Input(new ByteArrayInputStream(bytes));
                hessian2Input.setSerializerFactory(serializerFactory);
                try {
                    hessian2Input.startMessage();
                    Object o = hessian2Input.readObject();
                    hessian2Input.completeMessage();
                    hessian2Input.close();
                    System.out.println("[serial]"+o);
                    return o;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 千万分之的概率命中失败
     * 命中:准确率
     */
    private static final BloomFilter<String> hasNoFeedBackUser = BloomFilter.create(new Funnel<String>() {

        private static final long serialVersionUID = 1L;

        @Override
        public void funnel(String value, PrimitiveSink sink) {

            sink.putString(value, Charsets.UTF_8);
        }

    }, 1024*1024*32, 0.0000001d);

    public static void main(String[] args) throws InterruptedException, IOException {
        hasNoFeedBackUser.put("zhangwei");
        System.out.println(hasNoFeedBackUser.mightContain("zhangwei"));
        //发序列化错误
        CityDTO cityDTO = new CityDTO();
        cityDTO.setCityId(123);
        cityDTO.setCityName("济南");
        stringRedisTemplate.opsForValue().set("dw",cityDTO,12,TimeUnit.MINUTES);
        Thread.sleep(1000L);
        Object zw = stringRedisTemplate.opsForValue().get("dw");
        CityDTO bloomFilter = (CityDTO) zw;
        System.out.println("[应用]"+bloomFilter);

        stringRedisTemplate.opsForValue().set("zs",hasNoFeedBackUser,12,TimeUnit.MINUTES);
        Thread.sleep(1000L);
        Object zw1 = stringRedisTemplate.opsForValue().get("zs");
        BloomFilter bloom = (BloomFilter) zw1;
        System.out.println(bloom.mightContain("zhangwei"));
        System.out.println(bloom.mightContain("zhangwei11"));
        System.out.println("[应用]"+bloom);


    }
}
 

Redis的官方未提供Hessian序列化序列化模块,但可以通过使用开源的Java Hessian库实现Hessian序列化与反序列化使用步骤如下: 1. 下载Java Hessian库,将jar包添加到Java项目的classpath中。 2. 创建Hessian序列化工具类,将对象序列化成字节数组: ``` import com.caucho.hessian.io.HessianInput; import com.caucho.hessian.io.HessianOutput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class HessianSerializer { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HessianOutput output = new HessianOutput(baos); output.writeObject(obj); return baos.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); HessianInput input = new HessianInput(bais); return input.readObject(); } } ``` 3. 在Redis中设置Hessian序列化: ``` import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; public class HessianRedisSerializer implements RedisSerializer<Object> { @Override public byte[] serialize(Object obj) throws SerializationException { if (obj == null) { return new byte[0]; } try { return HessianSerializer.serialize(obj); } catch (IOException e) { throw new SerializationException("Hessian serialize error", e); } } @Override public Object deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } try { return HessianSerializer.deserialize(bytes); } catch (IOException e) { throw new SerializationException("Hessian deserialize error", e); } } } ``` 4. 在Redis配置文件中设置Hessian序列化: ``` spring.redis.serializer=com.example.redisserializer.HessianRedisSerializer ``` 以上就是Redis实现Hessian序列化序列化的简单实现方式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自驱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值