首页 > 代码库 > redis缓存

redis缓存

项目的首页面由于有大量的图片、文字等可变信息,之前没有使用缓存,首页访问起来比较慢,后来加入了oscache,最近想引进redis作为缓存。

搜帖子,按部就班的来做。

一.首先使用maven在项目中引入jedis client端:

<dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>2.1.0</version></dependency>

引入两个jar包,jedis-2.1.0.jar、commons-pool-1.5.5.jar。(注:如果引入的redis是2.6.2版本,commons-pool包版本不同,commons-pool2-2.0.jar)最主要是jedis配置不同。

当时也引入了另一个包,spring-data-redis:

<dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-redis</artifactId>    <version>1.1.1.RELEASE</version></dependency>

 其实,jedis和spring-data-redis都是redis的客户端。经过后来走弯路发现使用spring-data-redis写代码太过繁琐,例如:

public boolean add(final User user) {    @SuppressWarnings("unchecked")    boolean result = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {            RedisSerializer<String> serializer = getRedisSerializer();            connection.setNX(serializer.serialize("user:" + user.getId()),                    serializer.serialize(JSONObject.fromObject(user).toString()));            return true;        }    });    return result;}

 

每个key和value都必须是byte[],不能使用String存储,这样非常繁琐。而jedis就可以存储String值,非常方便。

二.下面是配置:

redis.properties

#最大分配的对象数redis.pool.maxActive=1024#最大能够保持idel状态的对象数redis.pool.maxIdle=200#当池内没有返回对象时,最大等待时间redis.pool.maxWait=1000#当调用borrow Object方法时,是否进行有效性检查redis.pool.testOnBorrow=true#IPredis.host=192.168.1.115#Portredis.port=6379#redis.pass=java2000_w1

applicationContext.xml

<context:property-placeholder location="classpath:redis.properties" /><!-- jedis 2.1配置 --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">    <property name="maxIdle" value="${redis.pool.maxIdle}" />    <property name="maxActive" value="${redis.pool.maxActive}" />    <property name="maxWait" value="${redis.pool.maxWait}" />    <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /></bean><bean id="jedisFactory" class="com.yzy.task.JedisFactory">    <property name="jedisPoolConfig" ref="jedisPoolConfig" />    <property name="host" value="${redis.host}" />    <property name="port" value="${redis.port}" /></bean>

 三.代码存储实现:

RedisCacheServiceImpl

public class RedisCacheServiceImpl implements RedisCacheService {    private PageInfo page = new PageInfo();    private JedisFactory jedisFactory;    private IndexLayoutService indexLayoutService;    public void addToCache() {        Jedis jedis = jedisFactory.getJedisInstance();        List<IndexLayout> indexLayoutList = new ArrayList<IndexLayout>();        indexLayoutList = indexLayoutService.getIndexLayoutList(page).getResultList();        for (IndexLayout indexLayout : indexLayoutList) {            String indexLayoutId = indexLayout.getId().toString();            Product product = indexLayout.getProduct();            String indexLayoutProductId = product.getId().toString();            String indexLayoutKey = "indexLayout:" + indexLayoutId + ":" + indexLayoutProductId;            Gson gson = new Gson();            String json = gson.toJson(product);            jedis.set(indexLayoutKey, json);        }    }    public List<Product> getCache() {        List<Product> productList = new ArrayList<Product>();        Jedis jedis = jedisFactory.getJedisInstance();                Gson gson = new Gson();        for (String key : jedis.keys("indexLayout:*")) {            Product product = gson.fromJson(jedis.get(key), Product.class);            productList.add(product);        }        return productList;    }    //getter、setter方法}

 

其中使用gson把java对象转化为json字符串形式存储到value中。

使用json-lib包总是提示:

2015-01-28 12:01:02  ERROR  com.opensymphony.xwork2.util.logging.commons.CommonsLogger.error(CommonsLogger.java:38)  Exception occurred during processing request: java.lang.reflect.InvocationTargetExceptionnet.sf.json.JSONException: java.lang.reflect.InvocationTargetException    at net.sf.json.JSONObject._fromBean(JSONObject.java:987)    at net.sf.json.JSONObject.fromObject(JSONObject.java:168)    at net.sf.json.JSONArray.fromObject(JSONArray.java:170)    at com.yzy.mall.service.impl.RedisCacheServiceImpl$1.doInRedis(RedisCacheServiceImpl.java:53)    at com.yzy.mall.service.impl.RedisCacheServiceImpl$1.doInRedis(RedisCacheServiceImpl.java:1)    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:181)    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:149)......

引入包没问题,至今还没有解决。

 

redis缓存