1. 程式人生 > >spring 整合 redis的配置

spring 整合 redis的配置

index row val return created log idea pass truct

  廢話不說,直接上代碼:

  1、先添加依賴包

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

  2、新建 applicationContext-redis.xml 文件

  在裏面配置 jedisPoolConfig, ShardedJedisPool(也可以配置JedisPool):

<?xml version="1.0" encoding="UTF-8"?>
<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"> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:resource/*.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="60000" /> <property name="maxIdle" value="1000" /> <property name="numTestsPerEvictionRun" value="1024"/> <property name="timeBetweenEvictionRunsMillis" value="30000" /> <property name="minEvictableIdleTimeMillis" value="-1" /> <property name="softMinEvictableIdleTimeMillis" value="10000" /> <property name="maxWaitMillis" value="1500"/> <property name="testOnBorrow" value="true" /> <property name="testWhileIdle" value="true"/> <property name="testOnReturn" value="false"/> <property name="jmxEnabled" value="true"/> <property name="jmxNamePrefix" value="youyuan"/> <property name="blockWhenExhausted" value="false"/> </bean> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"> <constructor-arg index="0" ref="jedisPoolConfig"/> <constructor-arg index="1"> <list> <!-- <bean name="slaver" class="redis.clients.jedis.JedisShardInfo"> <constructor-arg index="0" value="${redis.slaver.host}"/> <constructor-arg index="1" value="${redis.slaver.port}" type="int"/> </bean>--> <bean name="master" class="redis.clients.jedis.JedisShardInfo"> <constructor-arg index="0" value="${redis.master.host}"/> <constructor-arg index="1" value="${redis.master.port}" type="int"/> <property name="password" value="${redis.master.auth}"/> </bean> </list> </constructor-arg> </bean> <bean id="shardedRedisManager" class="com.jdd.core.redis.ShardedRedisManager"></bean> </beans>

  3、再創建一個緩存管理類 ShardedRedisManager:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.jdd.core.redis;

import com.jdd.core.log.LogExceptionStackTrace;
import com.jdd.core.utils.GfJsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.*;
import java.util.List;


public class ShardedRedisManager {
    @Autowired
    private ShardedJedisPool shardedJedisPool;
    private String host;
    private int port;
    private static final Logger logger = LoggerFactory.getLogger(ShardedRedisManager.class);

    public ShardedRedisManager() {
    }

    public String getHost() {
        return this.host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return this.port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public ShardedJedisPool getShardedJedisPool() {
        return this.shardedJedisPool;
    }

    private void returnResource(ShardedJedis sj) {
        sj.close();
    }

    private ShardedJedis getResource() {
        return this.shardedJedisPool.getResource();
    }

    private ShardedJedisPipeline pipelined(ShardedJedis sj) {
        return sj.pipelined();
    }

    public Long incr(String key) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            Long v = sj.incr(key);
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:incr key:{} execution time:{}ms", new Object[]{this.host, this.port, key, time});
            }

            Long var7 = v;
            return var7;
        } catch (Exception var11) {
            logger.error("command:incr key:{} ex={}", key, LogExceptionStackTrace.erroStackTrace(var11));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

        return null;
    }

    public String type(String key) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            String v = sj.type(key);
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:type key:{} execution time:{}ms", new Object[]{this.host, this.port, key, time});
            }

            String var7 = v;
            return var7;
        } catch (Exception var11) {
            logger.error("command:type key:{} ex={}", key, LogExceptionStackTrace.erroStackTrace(var11));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

        return null;
    }

    public Long incr(String key, Long integer) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            Long v = sj.incrBy(key, integer);
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:incr key:{} execution time:{}ms", new Object[]{this.host, this.port, key, time});
            }

            Long var8 = v;
            return var8;
        } catch (Exception var12) {
            logger.error("command:incr key:{} ex={}", key, LogExceptionStackTrace.erroStackTrace(var12));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

        return null;
    }

    public String get(String key) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            String v = sj.get(key);
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:get key:{} execution time:{}ms", new Object[]{this.host, this.port, key, time});
            }

            String var7 = v;
            return var7;
        } catch (Exception var11) {
            logger.error("command:get key:{} ex={}", key, LogExceptionStackTrace.erroStackTrace(var11));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

        return null;
    }

    public String set(String key, String value) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            String v = sj.set(key, value);
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:set key:{} execution time:{}ms", new Object[]{this.host, this.port, key, time});
            }

            String var8 = v;
            return var8;
        } catch (Exception var12) {
            logger.error("command:set key:{} ex={}", key, LogExceptionStackTrace.erroStackTrace(var12));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

        return null;
    }

    public void set(List<String> keys, List<String> values) {
        Long start = System.currentTimeMillis();
        ShardedJedis sj = null;

        try {
            sj = this.getResource();
            ShardedJedisPipeline pip = sj.pipelined();

            for(int i = 0; i < keys.size(); ++i) {
                pip.set((String)keys.get(i), (String)values.get(i));
            }

            pip.sync();
            Long end = System.currentTimeMillis();
            Long time = end - start;
            if (time > 500L) {
                logger.warn("ip:{} port:{} command:set list key:{} execution time:{}ms", new Object[]{this.host, this.port, GfJsonUtil.toJSONString(keys), time});
            }
        } catch (Exception var11) {
            logger.error("command:set key:{} ex={}", GfJsonUtil.toJSONString(keys), LogExceptionStackTrace.erroStackTrace(var11));
        } finally {
            if (sj != null) {
                this.returnResource(sj);
            }

        }

    }

}

  4、然後你就可以在service裏註入這個 ShardedRedisManager 類使用啦。

  結束!

spring 整合 redis的配置