springboot + redis项目实战

springboot + redis项目实战

1、添加依赖:


	org.springframework.boot
	spring-boot-starter-data-redis
	2.1.1.RELEASE


	redis.clients
	jedis
	2.9.0

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业务代码:

springboot + redis项目实战_第1张图片
testDao的本质是一个service,用来专门处理redis的序列化和发反序列化,以及对数据进行存取操作:

@Component
public class TestDaoImpl implements TestDao {

    @Autowired
    private RedisTemplate redisTemplate;

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

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

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

                return (List) SerializableUtils.unSerialize(value);
            }
        });
    }

    @Override
    public void saveUsers(List list) {
        redisTemplate.execute(new RedisCallback() {
            @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、运行结果:

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

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