1、复制jedis.properties
把jedis.properties文件复制到resources目录下
2、编写方法:List<Category> findAll()
-
先查Redis缓存
-
判断指定的键是否存在
-
如果存在
通过get获取缓存中JSON字符串 将JSON字符串转为List对象
-
如果不存在 则查询数据库,得到List集合
将List集合转成JSON字符串,存到Redis中
-
关闭Jedis连接
-
返回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中
-
获取Jedis连接
-
将验证码设置到Redis中,存活时间300秒
-
关闭连接
/**
* 发送短信
*/
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);
}