使用Jedis缓存优化系统查询

为了减少访问数据库的次数,设置jedis缓冲确实是个不错的办法,操作也很简单。

  • Redis下载好
  • 上手jedis的操作(String,hash,list,set等)
  • 编写工具类,jedis的连接池的工具类
package com.lcx.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/** 
* @author 作者 E-mail: 
* @version 创建时间:2020年5月16日 下午8:57:15 
* 类说明  jedisPool工具包
*/
public class JedisPoolUtils {

	private static JedisPool jedisPool;
	
	//类加载时读取配置文件
	static {
		InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
		//创建Properties对象
		Properties pro = new Properties();
		//关联文件
		try {
			pro.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//获取数据,设置到jedisPoolConfig中
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
		config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
		
		//初始化JedisPool
		jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
	}
	
	public  static Jedis getJedis() {
		return jedisPool.getResource();
	}
	
}

  • 在需要实现的地方调用就好了。对于那些不常改变的数据,在首次查询后可放在缓存中,以后的每次查询就可直接在缓存中查,大大减少访问数据库的次数。
    承接我之前的课设,我就在查询商品时用了这个缓存
@Override
	public String findJson(int tags) {
		// TODO Auto-generated method stub
		Jedis jedis = JedisPoolUtils.getJedis();
		String typename = StringUtil.createname("product", tags);
		String product_json=jedis.get(typename);
		//首次查询
		if(product_json==null) {
			System.out.println("首次查询jedis为空,要去数据库查了");
			//从数据库中找
			List<Product> tag_product = dao.findbytags(tags);
			//序列化
			ObjectMapper mapper = new ObjectMapper();
			try {
				product_json=mapper.writeValueAsString(tag_product);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jedis.set(typename,product_json);
			jedis.close();
		}
		return product_json;
	}

我这里还序列化了,发现多此一举,controller还是要转回list输出到界面┭┮﹏┭┮,直接存list不就好了吗~~~

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值