在Spring+SpringMVC+Mybatis+maven中集成redis

2018-01-02 19:16:21来源:CSDN作者:qq846999693人点击

分享

提示:
(1)省略了远程redis服务的搭建
(2)假定当前项目的开发环境为Spring+SpringMVC+Mybatis+maven

1、在pom.xml文件中引入jedis依赖(用于java开发)

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

2、 新建一个redis.propertis属性文件,用于存储redis的连接信息和配置信息

#远程主机地址redis.hostname=填写你redis的主机地址#redis服务端口redis.port=6379#redis数据库redis.database=0#最大连接数redis.pool.maxActive=100#最大空闲数redis.pool.maxIdle=20#最大等待时间redis.pool.maxWait=3000redis.pool.testOnBorrow=true

3、 编写用于java开发的jedis工具类

(1) jedisPoolWriper
作用:获取和注入redis连接处对象

import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisPoolWriper {    //Redis连接池对象    private JedisPool jedisPool;    public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host,            final int port) {        try {            jedisPool = new JedisPool(poolConfig, host, port);        } catch (Exception e) {            e.printStackTrace();        }    }     //获取Redis连接池对象    public JedisPool getJedisPool() {        return jedisPool;    }    // 注入Redis连接池对象    public void setJedisPool(JedisPool jedisPool) {        this.jedisPool = jedisPool;    }}

(2) jedisUtil
作用:用于Service层操作redis

public class JedisUtil {    /**     * 缓存生存时间     */    private final int expire = 60000;    /** 操作Key的方法 */    public Keys KEYS;    /** 对存储结构为String类型的操作 */    public Strings STRINGS;    /** 对存储结构为List类型的操作 */    public Lists LISTS;    /** 对存储结构为Set类型的操作 */    public Sets SETS;    /** 对存储结构为HashMap类型的操作 */    public Hash HASH;    /** Redis连接池对象 */    private JedisPool jedisPool;    /**     * 获取redis连接池     *      * @return     */    public JedisPool getJedisPool() {        return jedisPool;    }    /**     * 设置redis连接池     *      * @return     */    public void setJedisPool(JedisPoolWriper jedisPoolWriper) {        this.jedisPool = jedisPoolWriper.getJedisPool();    }    /**     * 从jedis连接池中获取获取jedis对象     *      * @return     */    public Jedis getJedis() {        return jedisPool.getResource();    }    /**     * 设置过期时间     *      * @author xiangze     * @param key     * @param seconds     */    public void expire(String key, int seconds) {        if (seconds <= 0) {            return;        }        Jedis jedis = getJedis();        jedis.expire(key, seconds);        jedis.close();    }    public void expire(String key) {        expire(key, expire);    }        public class Keys {        public String flushAll() {            Jedis jedis = getJedis();            String stata = jedis.flushAll();            jedis.close();            return stata;        }        public String rename(String oldkey, String newkey) {            return rename(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey));        }        public long renamenx(String oldkey, String newkey) {            Jedis jedis = getJedis();            long status = jedis.renamenx(oldkey, newkey);            jedis.close();            return status;        }        public String rename(byte[] oldkey, byte[] newkey) {            Jedis jedis = getJedis();            String status = jedis.rename(oldkey, newkey);            jedis.close();            return status;        }        public long expired(String key, int seconds) {            Jedis jedis = getJedis();            long count = jedis.expire(key, seconds);            jedis.close();            return count;        }        public long expireAt(String key, long timestamp) {            Jedis jedis = getJedis();            long count = jedis.expireAt(key, timestamp);            jedis.close();            return count;        }        public long ttl(String key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            long len = sjedis.ttl(key);            sjedis.close();            return len;        }        public long persist(String key) {            Jedis jedis = getJedis();            long count = jedis.persist(key);            jedis.close();            return count;        }        public long del(String... keys) {            Jedis jedis = getJedis();            long count = jedis.del(keys);            jedis.close();            return count;        }        public long del(byte[]... keys) {            Jedis jedis = getJedis();            long count = jedis.del(keys);            jedis.close();            return count;        }        public boolean exists(String key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            boolean exis = sjedis.exists(key);            sjedis.close();            return exis;        }        public List<String> sort(String key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            List<String> list = sjedis.sort(key);            sjedis.close();            return list;        }        public List<String> sort(String key, SortingParams parame) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            List<String> list = sjedis.sort(key, parame);            sjedis.close();            return list;        }        public String type(String key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            String type = sjedis.type(key);            sjedis.close();            return type;        }        public Set<String> keys(String pattern) {            Jedis jedis = getJedis();            Set<String> set = jedis.keys(pattern);            jedis.close();            return set;        }    }        public String get(String key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            String value = sjedis.get(key);            sjedis.close();            return value;        }        public byte[] get(byte[] key) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            byte[] value = sjedis.get(key);            sjedis.close();            return value;        }        public String set(String key, String value) {            return set(SafeEncoder.encode(key), SafeEncoder.encode(value));        }        public String set(String key, byte[] value) {            return set(SafeEncoder.encode(key), value);        }        public String set(byte[] key, byte[] value) {            Jedis jedis = getJedis();            String status = jedis.set(key, value);            jedis.close();            return status;        }        public String setEx(String key, int seconds, String value) {            Jedis jedis = getJedis();            String str = jedis.setex(key, seconds, value);            jedis.close();            return str;        }        public String setEx(byte[] key, int seconds, byte[] value) {            Jedis jedis = getJedis();            String str = jedis.setex(key, seconds, value);            jedis.close();            return str;        }        public long setnx(String key, String value) {            Jedis jedis = getJedis();            long str = jedis.setnx(key, value);            jedis.close();            return str;        }        public long setRange(String key, long offset, String value) {            Jedis jedis = getJedis();            long len = jedis.setrange(key, offset, value);            jedis.close();            return len;        }        public long append(String key, String value) {            Jedis jedis = getJedis();            long len = jedis.append(key, value);            jedis.close();            return len;        }        public long decrBy(String key, long number) {            Jedis jedis = getJedis();            long len = jedis.decrBy(key, number);            jedis.close();            return len;        }        public long incrBy(String key, long number) {            Jedis jedis = getJedis();            long len = jedis.incrBy(key, number);            jedis.close();            return len;        }        public String getrange(String key, long startOffset, long endOffset) {            // ShardedJedis sjedis = getShardedJedis();            Jedis sjedis = getJedis();            String value = sjedis.getrange(key, startOffset, endOffset);            sjedis.close();            return value;        }        public String getSet(String key, String value) {            Jedis jedis = getJedis();            String str = jedis.getSet(key, value);            jedis.close();            return str;        }        public List<String> mget(String... keys) {            Jedis jedis = getJedis();            List<String> str = jedis.mget(keys);            jedis.close();            return str;        }        public String mset(String... keysvalues) {            Jedis jedis = getJedis();            String str = jedis.mset(keysvalues);            jedis.close();            return str;        }        public long strlen(String key) {            Jedis jedis = getJedis();            long len = jedis.strlen(key);            jedis.close();            return len;        }    }}

6、 应用于Service层

接口:

public interface AreaService {    // 定义区域信息key        public static final String AREALISTKEY = "arealist";    /**     * 获取区域列表     *      * @return     */    List<Area> getAreaList();}

实现类:

@Servicepublic class AreaServiceImpl implements AreaService {    // 自动注入DAO的实现    @Autowired    private AreaDao areaDao;    @Autowired    private JedisUtil.Keys jedisKeys;    @Autowired    private JedisUtil.Strings jedisStrings;    @Override    @Transactional    public List<Area> getAreaList() {        String key = AREALISTKEY;        // 用于接收区域对象信息        // 定义接收对象        List<Area> areaList = null;        // 定义jackson数据转换操作类        ObjectMapper mapper = new ObjectMapper();        // 判断redis中key是否存在        // 1、存在,直接从redis中取数据        // 2、不存在,查询数据库,获取数据,并把数据更新到redis中        if (!jedisKeys.exists(key)) {            // 若不存在,则从数据库里面取出相应数据            areaList = areaDao.queryArea();            // 将相关的实体类集合转换成string,存入redis里面对应的key中            String jsonString;            try {                jsonString = mapper.writeValueAsString(areaList);            } catch (JsonProcessingException e) {                e.printStackTrace();                throw new AreaOperationException(e.getMessage());            }            jedisStrings.set(key, jsonString);        } else {            // 若存在,则直接从redis里面取出相应数据            String jsonString = jedisStrings.get(key);            // 指定要将string转换成的集合类型            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class);            try {                // 将相关key对应的value里的的string转换成java对象的实体类集合                areaList = mapper.readValue(jsonString, javaType);            } catch (JsonParseException e) {                e.printStackTrace();                throw new AreaOperationException(e.getMessage());            } catch (JsonMappingException e) {                e.printStackTrace();                throw new AreaOperationException(e.getMessage());            } catch (IOException e) {                e.printStackTrace();                throw new AreaOperationException(e.getMessage());            }        }        return areaList;    }}

7、测试,在Service实现类打断点,用debug模式启动测试类进行调试

    @Test    public void testGetAreaList() {        List<Area> areaList = areaService.getAreaList();        System.out.println(areaList.get(1).getAreaName());    }

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台