springboot + redis项目实战

springboot + redis项目实战

1、添加依赖:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>

2、添加RedisConfiguration :

@Configuration
public class RedisConfiguration {

    @Value("${spring.redis.host}")
    private String hostName;

    @Value("${spring.redis.port}")
    private Integer port;

    @Value("${spring.redis.password}")
    private String password;

    /**
     * JedisConnectionFactory 中注入 redis host port password.
     *
     * @return JedisConnectionFactory对象
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(hostName, port);
        config.setPassword(RedisPassword.of(password));

        JedisClientConfiguration.JedisClientConfigurationBuilder clientConfiguration = JedisClientConfiguration.builder();
        clientConfiguration.connectTimeout(Duration.ofMillis(0));
        JedisConnectionFactory factory = new JedisConnectionFactory(config, clientConfiguration.build());

        return factory;
    }

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    /**
     * RedisTemplate 中注入JedisConnectionFactory.
     *
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate redisTemplate(@Qualifier("stringRedisSerializer") StringRedisSerializer stringRedisSerializer,
                                       @Qualifier("jedisConnectionFactory") JedisConnectionFactory jedisConnectionFactory) {

        RedisTemplate rt = new RedisTemplate();
        rt.setConnectionFactory(jedisConnectionFactory);
        rt.setKeySerializer(stringRedisSerializer);
        rt.setHashKeySerializer(stringRedisSerializer);
        rt.setHashValueSerializer(stringRedisSerializer);
        rt.setValueSerializer(stringRedisSerializer);

        return rt;
    }
}

3、添加序列化工具:

public class SerializableUtils {
    /**
     * 序列化java对象
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream objectOutputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 反序列化java对象
     *
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes) {
        ByteArrayInputStream byteArrayInputStream;
        try {
            byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream);
            return ois.readObject();
        } catch (Exception e) {
            return null;
        }
    }
}

4、创建实体类:

注意:实体类一定要实现Serializable 接口。

public class User implements Serializable {

    private String id;
    private String userName;
    private String phoneNumber;
    private String password;
    private Boolean status;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }
}

5、service业务代码:

在这里插入图片描述
testDao的本质是一个service,用来专门处理redis的序列化和发反序列化,以及对数据进行存取操作:

@Component
public class TestDaoImpl implements TestDao {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<User> getUsers() {
        return (List<User>) redisTemplate.execute(new RedisCallback<List<User>>() {
            @Override
            public List<User> doInRedis(RedisConnection connection) throws DataAccessException {

                byte[] key = redisTemplate.getStringSerializer().serialize("users");

                byte[] value = connection.get(key);

                return (List<User>) SerializableUtils.unSerialize(value);
            }
        });
    }

    @Override
    public void saveUsers(List<User> list) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {

                byte[] bKey = redisTemplate.getStringSerializer().serialize("users");

                byte[] bValue = SerializableUtils.serialize(list);

                connection.set(bKey, bValue);

                return null;
            }
        });
    }
}

6、运行结果:

直接从数据库获取:
在这里插入图片描述
第二次从redis获取:
在这里插入图片描述
运行时间有明显的差别。
redis中存储的经过序列化后的数据:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值