javaweb中应用redis

来源:互联网 发布:python关键字是什么 编辑:程序博客网 时间:2024/05/20 05:22

背景:         

     redis想必大家肯定已经熟悉的不能再熟悉了,所以小编就不再赘述各种好处了,就直接说怎么用吧。这个是之前javaweb项目中用到的,也算是个小小的回顾吧。 

  1、首先导入Jedis的jar包


2、编写工具类:

public class JedisUtils {//定义连接池配置对象private static final JedisPoolConfig config;//定义连接池对象private static final JedisPool pool;static{//创建连接池配置对象config=new JedisPoolConfig();//最大连接数config.setMaxTotal(30);//最大空闲连接数config.setMaxIdle(2);//创建连接池对象:pool=new JedisPool(config,"192.168.42.128",6379);}//提供一个获得jedis的方法public static Jedis getJedis(){return pool.getResource();}//提供关闭Jedis的方法public static void closeJedis(Jedis jedis){if (jedis !=null) {jedis.close();}}}

3、业务层从缓存中获取数据

public String findByAjax() throws SQLException {Jedis jedis = null;try {// 获得Jedis的对象jedis = JedisUtils.getJedis();// 从缓存中获取数据String value = jedis.get("category_list");if (value == null) {// 缓存中没有数据CategoryDao categoryDao = (CategoryDao) BeanFactory.getBean("categoryDao");List<Category> categoryList = categoryDao.findAll();// 将list转成jsonJSONArray jsonArray = JSONArray.fromObject(categoryList);jedis.set("category_list", jsonArray.toString());return jedis.get("category_list");} else {return value;}} catch (Exception e) {e.printStackTrace();} finally {JedisUtils.closeJedis(jedis);}return null;}

4、DAO层:

@Overridepublic List<Category> findAll() throws SQLException {  String sql="select * from category";  return new QueryRunner(JDBCUtils.getDataSource()).query(sql, new BeanListHandler<Category>(Category.class));}

小结:

      本篇博客用于记录使用redis的过程。



   

0 0
原创粉丝点击