SpringBoot--使用redis做缓存(2)

一、redis做缓存的优缺点

(1)优点:简单灵活、数据结构丰富、高速读写。

(2)缺点:持久化、要尽量避免或者设计机制保障。存储成本高,存储在内存中,从而要尽量避免使用redis进行大量数据存储。

二、示例

本文使用Spring的RedisTemplate来操作Redis。采用SpringBoot对redis的自动配置。

(1)配置redis的连接信息。

spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0

(2)Redis配置类添加RedisTemplate。

package com.liutao.config;

import com.liutao.utils.RedisObjectSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 *
 * @author LIUTAO
 * @version 2017/5/16
 * @see
 */
@Configuration
public class RedisConfig {
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

(3)编写redis客户端。

package com.liutao.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis客户端工具类
 *
 * @author LIUTAO
 * @version 2017/5/15
 * @see
 */
@Component
public class RedisClient {
    private static Logger logger = LoggerFactory.getLogger(RedisClient.class);
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存数据进入缓存
     *
     * @param key          键
     * @param value        值
     * @param cacheSeconds 缓存时间
     */
    public void putObject(final String key, final Object value, final int cacheSeconds) {
        redisTemplate.opsForValue().set(key, value, cacheSeconds, TimeUnit.SECONDS);
    }

    /**
     * get操作
     *
     * @param key 键
     * @return
     */
    public Object getObject(final String key) {
        return redisTemplate.opsForValue().get(key);
    }


    /**
     * 从缓存中删除对象
     *
     * @param key 键
     * @return
     */
    public int del(final String key) {
        try {
            redisTemplate.delete(key);
            return 1;
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * 判断缓存数据是否存在
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
}

(4)编写测试Controller

package com.liutao.controller;

import com.liutao.entity.User;
import com.wordnik.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.liutao.utils.RedisClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户控制层
 *
 * @author LIUTAO
 * @version 2017/3/29
 * @see
 */
@RestController
@Api(value = "test")
@RequestMapping("/liutao/v1")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private RedisClient redisClient;
    /**
     * 缓存测试
     *
     * @return
     * @author SHANHY
     * @create 2016年9月12日
     */
    @GetMapping("/redisTest")
    public String redisTest() {
        try {
            redisClient.putObject("test-key", "redis测试内容", 5);// 缓存有效期5秒
            logger.info("从Redis中读取数据:" + redisClient.getObject("test-key").toString());
            TimeUnit.SECONDS.sleep(3);
            logger.info("等待3秒后从Redis中读取数据:" + redisClient.getObject("test-key").toString());
            TimeUnit.SECONDS.sleep(3);
            logger.info("等待5秒后尝试读取过期的数据:" + redisClient.getObject("test-key"));

            redisClient.putObject("user",new User("张三","zs123"),10);
            logger.info("从Redis中读取数据User:" + redisClient.getObject("user"));

            List<String> list = new ArrayList<>();
            list.add("张飞");
            list.add("刘备");
            list.add("关于");
            redisClient.putObject("list",list,5);
            TimeUnit.SECONDS.sleep(3);
            logger.info("从Redis中读取数据User:" + redisClient.getObject("list"));
            TimeUnit.SECONDS.sleep(3);
            logger.info("从Redis中读取数据list:" + redisClient.getObject("list"));

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "OK";
    }
}

(5)运行测试结果

2017-05-17 11:38:57.513 [http-nio-8080-exec-1] INFO  org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-05-17 11:38:57.608 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 从Redis中读取数据:redis测试内容
2017-05-17 11:39:00.608 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 等待3秒后从Redis中读取数据:redis测试内容
2017-05-17 11:39:03.609 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 等待5秒后尝试读取过期的数据:null
2017-05-17 11:39:03.612 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 从Redis中读取数据User:User{name='张三', password='zs123'}
2017-05-17 11:39:06.614 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 从Redis中读取数据User:[张飞, 刘备, 关于]
2017-05-17 11:39:09.614 [http-nio-8080-exec-1] INFO  com.liutao.controller.UserController - 从Redis中读取数据list:null

三、总结

从以上测试结果可以看出目前缓存已经生效。采用此方法不仅仅可以缓存字符串而且针对对象和集合都可以进行缓存。项目代码参考地址SpringBoot中使用redis缓存


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值