redis优化导航条举例

1、复制jedis.properties

把jedis.properties文件复制到resources目录下

2、编写方法:List<Category> findAll()

  1. 先查Redis缓存

  2. 判断指定的键是否存在

  3. 如果存在

    通过get获取缓存中JSON字符串 将JSON字符串转为List对象

  4. 如果不存在 则查询数据库,得到List集合

    将List集合转成JSON字符串,存到Redis中

  5. 关闭Jedis连接

  6. 返回List对象

3、代码

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.travel.dao.CategoryDao;
import com.itheima.travel.domain.Category;
import com.itheima.travel.service.CategoryService;
import com.itheima.travel.utils.DaoInstanceFactory;
import com.itheima.travel.utils.JedisUtils;
import lombok.SneakyThrows;
import redis.clients.jedis.Jedis;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {

    private CategoryDao categoryDao = DaoInstanceFactory.getBean(CategoryDao.class);

    /**
     * 查询所有的线路分类
     */
    @SneakyThrows
    @Override
    public List<Category> findAll() {
        List<Category> list = null;

        ObjectMapper mapper = new ObjectMapper();
        //1.获取jedis连接对象
        Jedis jedis = JedisUtils.getJedis();
        //2.从jedis中获取分类的json字符串
        String categories = jedis.get("categories");
        //3.如果存在,将json转成List对象
        if (categories != null) {
            list = mapper.readValue(categories, List.class);
        }
        //4.如果不存在,从dao中查询
        else {
            list = categoryDao.findAll();
            //5.将List转成json,写到redis中去
            String json = mapper.writeValueAsString(list);
            jedis.set("categories", json);
        }
        //6.关闭连接对象
        jedis.close();
        return list;
    }
}

 

 

2 发送短信

如果短信发送成功,将验证码放在Redis中

  1. 获取Jedis连接

  2. 将验证码设置到Redis中,存活时间300秒

  3. 关闭连接

/**
 * 发送短信
 */
protected void sendSms(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取会话对象
    HttpSession session = request.getSession();
    //获取手机号
    String telephone = request.getParameter("telephone");
    //生成6位数字的验证码
    String authCode = RandomStringUtils.randomNumeric(6);
    System.out.println("验证码:" + authCode);
    //调用业务层发送
    ResultInfo resultInfo = userService.sendSms(telephone, authCode);
    //判断发送结果
    if (resultInfo.getSuccess()) {
        //前缀加电话号码为键,值就是验证码
        //session.setAttribute("smsCode_" + telephone, authCode);
        //放在redis中
        Jedis jedis = JedisUtils.getJedis();
        //设置为20秒
        jedis.setex("smsCode_" + telephone, 20, authCode);
        jedis.close();
    }
    //将结果打印到浏览器
    printJsonString(response, resultInfo);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值