reids的使用

一、概述

redis:
(1)redis可以存储用户信息(session);
(2)redis可以存储购物车数据;
(3)redis可以存储条件检索的商品数据(k:v);
  注:Redis API参考 redisdoc.comredis使用教程

redis中有什么样的命令,jedis中就有与之对应的方法。

分类商品列表:
(1)用分类id作为key
(2)用商品sku对象集合作为value
(3)将商品缓存数据放入到redis中的zset里
    检索结果需要排序
    检索结果需要分页

二、使用步骤

引入依赖:

<!-- redis工具包 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

JedisPoolUtils:连接redis的工具类

package com.atguigu.util;

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

public class JedisPoolUtils {

    public static JedisPoolConfig c = new JedisPoolConfig(); // 连接池配置
    public static JedisPool jedisPool = null; // 连接池

    static {
        // c.setBlockWhenExhausted(true); // 连接耗尽则阻塞
        c.setLifo(true); // 后进先出
        c.setMaxIdle(10); // 最大空闲连接数为10
        c.setMinIdle(0); // 最小空闲连接数为0
        c.setMaxTotal(100); // 最大连接数为100
        c.setMaxWaitMillis(-1); // 设置最大等待毫秒数:无限制
        c.setMinEvictableIdleTimeMillis(180); // 逐出连接的最小空闲时间:30分钟
        c.setTestOnBorrow(true); // 获取连接时是否检查连接的有效性:是
        c.setTestWhileIdle(true); // 空闲时是否检查连接的有效性:是

        jedisPool = new JedisPool(c, MyPropertiesUtil.getMyProperty("redis.properties", "url"), 6379); // 初始化连接池
    }

    /**
     * 获取Jedis连接
     * 
     * @return Jedis连接
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

}
View Code

MyPropertiesUtil:读取配置文件的工具类

package com.atguigu.util;

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

/**
 * 读配置文件的工具类
 * @author doublening
 *
 */
public class MyPropertiesUtil {

    public static String getMyProperty(String properties, String key) {

        Properties properties2 = new Properties();

        InputStream resourceAsStream = MyPropertiesUtil.class.getClassLoader().getResourceAsStream(properties);

        try {
            properties2.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String property = properties2.getProperty(key);

        return property;

    }

}
View Code

redis.properties:redis连接配置文件

url=127.0.0.1

猜你喜欢

转载自www.cnblogs.com/shiyun32/p/10992134.html
今日推荐