WEB项目,使用redis做缓存小案例

1.需求场景

展示实时数据

2.项目环境

Spring spring mvc mybatis

3.实现步骤

(1)链接redis

    public static Jedis getJedisConnection() {
        String redishost = "127.0.0.1";
        int redisport = 6379;// redis的端口
        int redistimeout = 2000;// redis超时时间
        int redisdatabase = 0;// redis的db
        Jedis jedis = null;
        try {
            jedis = new Jedis(redishost, redisport, redistimeout);
        } catch (Exception e) {
            System.out.println("连接redis报错!!");
        }
        if (redisdatabase != 0) {
            try {
                jedis.select(redisdatabase);
            } catch (Exception e) {
                System.out.println("redisdatabase error");
            }
        }
        return jedis;
    }

(2)redis写入数据

public void writeRedisData(){
try{
	//数据库获取数据
	List data = RedisCaceDataService.getRedisCacheData();
	//获得redis链接
	Jedis jedis = getJedisConnection();
	//写入数据
	 for(int i=0;i

(3)redis获取数据

/***
* 
* @Title:  getRealTimeData
* @Description: TODO 每个时间点的数据
* @param data
* @return
*/
public static List getRealTimeData(String key){
	List list = new ArrayList();
	Jedis jedis = getJedisConnection();
	long all_pv = 0;
	long ip_num = 0;
	long uv = 0;
	try{
		RedisEntityVO mop = new RedisEntityVO();
		pv = Long.parseLong(jedis.get(key+ "_pv"));
		uv = Long.parseLong(jedis.get(key+ "_uv");
		ip = Long.parseLong(jedis.get(key+ "_ip_num");
		e.setAllpv(Integer.parseInt(String.valueOf(all_pv)));
		e.setAlluv(Integer.parseInt(String.valueOf(uv)));
		e.setAllip(Integer.parseInt(String.valueOf(ip_num)));
		System.out.println("pv \t"+pv+"\t ip"+ip+"\t uv"+uv);
		list.add(e);
	}catch(exception e){
 		e.printStackTrace();
	} 
   jedis.close();
return list;
}

(3)测试

public static void main(String[] args) {
	String time="2018030101";
	RedisUtil.getRealTimeData(time);
		 
	}

你可能感兴趣的:(SSH/SSM)