Jedis整合到SpringMVC

来源:互联网 发布:charles能在windows 编辑:程序博客网 时间:2024/06/06 05:39

添加配置文件

applicationContext-redis.xml

配置文件内容

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 构建连接池配置信息 -->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <!-- 最大连接数 -->        <property name="maxTotal" value="${redis.maxTotal}"/>    </bean>    <bean id="jedisShardInfo1" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node1.ip}" />        <constructor-arg index="1" value="${redis.node1.port}"            type="int" />    </bean>    <bean id="jedisShardInfo2" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node2.ip}" />        <constructor-arg index="1" value="${redis.node2.port}"            type="int" />    </bean>    <bean id="jedisShardInfo3" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node3.ip}" />        <constructor-arg index="1" value="${redis.node3.port}"            type="int" />    </bean>    <!-- 定义集群连接池 -->    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" destroy-method="close">        <!-- 第一个参数 -->        <constructor-arg index="0" ref="jedisPoolConfig"/>        <constructor-arg index="1">            <list>                <ref bean="jedisShardInfo1" />                <ref bean="jedisShardInfo2" />                <ref bean="jedisShardInfo3" />            </list>        </constructor-arg>    </bean></beans>

增加属性文件 redis.properties,需要在spring的配置文件中 读取该属性文件。

redis.maxTotal=50redis.node1.ip=192.168.58.129redis.node1.port=6379redis.node2.ip=192.168.58.129redis.node2.port=6380redis.node3.ip=192.168.58.128redis.node3.port=6379

为整个项目添加一个工具类,这这是一个伪Service

package com.jt.common.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import redis.clients.jedis.ShardedJedis;import redis.clients.jedis.ShardedJedisPool;@Servicepublic class RedisService {    //有的工程需要,有的工程不需要。设置required=false,有就注入,没有就不注入。    @Autowired(required = false)    private ShardedJedisPool shardedJedisPool;    private <T> T execute(Function<ShardedJedis, T> function) {        ShardedJedis shardedJedis = null;        try {            // 从连接池中获取到jedis分片对象            shardedJedis = shardedJedisPool.getResource();            return function.execute(shardedJedis);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (null != shardedJedis) {                // 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态                shardedJedis.close();            }        }        return null;    }    /**     * 保存数据到redis中     *      * @param key     * @param value     * @return     */    public String set(final String key, final String value) {        return this.execute(new Function<ShardedJedis, String>() {            public String execute(ShardedJedis shardedJedis) {                return shardedJedis.set(key, value);            }        });    }    /**     * 保存数据到redis中,生存时间单位是:秒     *      * @param key     * @param value     * @param seconds     * @return     */    public String set(final String key, final String value, final Integer seconds) {        return this.execute(new Function<ShardedJedis, String>() {            public String execute(ShardedJedis shardedJedis) {                String result = shardedJedis.set(key, value);                shardedJedis.expire(key, seconds);//设置生存时间                return result;            }        });    }    /**     * 从redis中获取数据     *      * @param key     * @return     */    public String get(final String key) {        return this.execute(new Function<ShardedJedis, String>() {            public String execute(ShardedJedis shardedJedis) {                return shardedJedis.get(key);            }        });    }    /**     * 设置key生存时间,单位:秒     *      * @param key     * @param seconds     * @return     */    public Long expire(final String key, final Integer seconds) {        return this.execute(new Function<ShardedJedis, Long>() {            public Long execute(ShardedJedis shardedJedis) {                return shardedJedis.expire(key, seconds);            }        });    }    /**     * 从redis中删除数据     *      * @param key     * @return     */    public Long del(final String key) {        return this.execute(new Function<ShardedJedis, Long>() {            public Long execute(ShardedJedis shardedJedis) {                return shardedJedis.del(key);            }        });    }}

这样我们的整合工作就已经完成了,在项目中就可以添加redis的缓存了

package com.jt.manage.controller.web;import org.apache.commons.lang3.StringUtils;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.jt.common.service.RedisService;import com.jt.manage.pojo.Item;import com.jt.manage.pojo.ItemDesc;import com.jt.manage.service.ItemService;@Controllerpublic class WebItemController {    @Autowired    private ItemService itemService;    @Autowired    private RedisService redisService;    private static final ObjectMapper MAPPER=new ObjectMapper();     private static Logger log=Logger.getLogger(WebItemController.class);    @RequestMapping("/web/item/{itemId}")    @ResponseBody //后台系统返回的都是json串    public Item getItem(@PathVariable Long itemId){        //读        String key="JT_ITEM"+itemId;        String jsonData=redisService.get(key);        if(StringUtils.isNoneEmpty(jsonData)){            try {                return MAPPER.readValue(jsonData, Item.class);            } catch (Exception e) {                log.error(e.getMessage());            }        }        Item item = itemService.queryById(itemId);        //写        try {            //需要将item转为String类型的数据            redisService.set(key, MAPPER.writeValueAsString(item));        } catch (JsonProcessingException e) {            log.error(e.getMessage());        }        return item;    }    //"http://manage.jt.com/web/itemdesc/"+itemId;    @RequestMapping("/web/itemDesc/{itemId}")    @ResponseBody    public ItemDesc getItemDesc(@PathVariable Long itemId){        return itemService.getItemDescByItemId(itemId);    }}
0 0
原创粉丝点击