springMvc 舊項目遷移 springBoot ,Jedis配置

springMvc 舊項目遷移 springBoot ,原代碼中的Jedis配置轉化爲springBoot配置

在原項目中的Jedis配置,寫在是spring的applicationContext.xml中,進行bean的注入

properties配置如下

#redis config
redis.cache.hostName=127.0.0.1
redis.cache.port=6379
redis.cache.password=123456
redis.cache.timeout=2000
redis.cache.databaseIndex=0
redis.cache.maxIdle=300
redis.cache.minIdle=10
redis.cache.testOnBorrow=true
redis.cache.testOnReturn=true
redis.cache.testWhileIdle=true
redis.cache.maxWaitMillis=1000

xml配置如下

<!-- redis連接池 -->
	<bean id="cacheJedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" scope="singleton">
		<!--最大空閒連接數 -->
		<property name="maxIdle" value="${redis.session.maxIdle}" />
		<!--初始化連接數 -->
		<property name="minIdle" value="${redis.session.minIdle}" />
		<!--對拿到的connection進行validateObject校驗 -->
		<property name="testOnBorrow" value="${redis.session.testOnBorrow}" />
		<!--在進行returnObject對返回的connection進行validateObject校驗 -->
		<property name="testOnReturn" value="${redis.session.testOnReturn}" />
		<!--定時對線程池中空閒的鏈接進行validateObject校驗 -->
		<property name="testWhileIdle" value="${redis.session.testWhileIdle}" />
		<!-- 最大等待時間 -->
		<property name="maxWaitMillis" value="${redis.cache.maxWaitMillis}" />
	</bean>

	<!-- 配置redis共享連接池,業務層主要通過該bean訪問redis服務器 -->
	<bean id="cacheJedisPool" class="redis.clients.jedis.JedisPool" scope="singleton">
		<!-- jedisPoolConfig -->
		<constructor-arg index="0" ref="cacheJedisPoolConfig" />
		<!-- ip -->
		<constructor-arg index="1" value="${redis.cache.hostName}" type="java.lang.String" />
		<!-- port -->
		<constructor-arg index="2" value="${redis.cache.port}" type="int" />
		<!-- timeout -->
		<constructor-arg index="3" value="${redis.cache.timeout}" type="int" />
		<!-- passowrd -->
		<constructor-arg index="4" value="${redis.cache.password}" type="java.lang.String" />
		<!-- databaseIndex -->
		<constructor-arg index="5" value="${redis.cache.databaseIndex}" type="int" />
	</bean>
    
    <!-- 自定義的工具類,實現redis的增刪改 -->
	<bean id="systemCache" class="com.**.RedisClient" scope="singleton">
		<property name="jedisPool" ref="cacheJedisPool" />
	</bean>

RedisClient 中實現Jedis的增刪改

import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.landicorp.core.exception.BusinessException;

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

public class RedisClient {

	private static final Logger logger = Logger.getLogger(RedisClient.class);
	/**
	 * 20分鐘過期
	 */
	public static int defaultExpireTime = 20 * 60;
	/**
	 * xml配置文件中注入
	 */
	private JedisPool jedisPool;
	/**
	 * 格式化規則
	 */
	private ObjectMapper mapper;

	public RedisClient() {
		mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:ss:mm.SSS"));
		mapper.setSerializationInclusion(Include.NON_NULL);
	}

	public <T> T get(String key, Class<T> clazz, Class<?>... parametricType) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			if (!jedis.exists(key)) {
				return null;
			}
			String result = jedis.get(key);
			if (result == null) {
				return null;
			}
			if (parametricType == null || parametricType.length == 0) {
				return mapper.readValue(result, clazz);
			} else {
				return mapper.readValue(result, mapper.getTypeFactory().constructParametricType(clazz, parametricType));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

	public boolean delete(String key) {
		Jedis jedis = jedisPool.getResource();
		jedis.del(key);
		jedis.close();
		return true;
	}

	public boolean flushAll() {
		Jedis jedis = jedisPool.getResource();
		jedis.flushAll();
		jedis.close();
		return true;
	}

	public boolean flushAll(int delay) {
		throw new BusinessException("不支持延期清除所有");
	}

	public <T> boolean add(String key, T value) {
		return set(key, value, defaultExpireTime);
	}

	public <T> boolean add(String key, T value, int expiry) {
		return set(key, value, expiry);
	}

	public <T> boolean set(String key, T value) {
		return set(key, value, defaultExpireTime);
	}

	public <T> boolean set(String key, T value, int expiry) {
		try {
			Jedis jedis = jedisPool.getResource();
			if (expiry == 0) {
				jedis.set(key, mapper.writeValueAsString(value));
			} else {
				jedis.setex(key, expiry, mapper.writeValueAsString(value));
			}
			jedis.close();
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

}

修改爲SpringBoot項目,由於捨棄了xml,需要自行定義 @Configuration

properties參數添加進springBoot的application.properties

添加JedisConfig.java 用於注入Jedis

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.redis.JedisPool;
import redis.clients.redis.JedisPoolConfig;


@Configuration
public class JedisConfig extends CachingConfigurerSupport {

    private Logger logger = LoggerFactory.getLogger(JedisConfig.class);

    @Value("${redis.cache.hostName}")
    private String host;

    @Value("${redis.cache.port}")
    private int port;

    @Value("${redis.cache.password}")
    private String password;

    @Value("${redis.cache.timeout}")
    private int timeout;

    @Value("${redis.cache.databaseIndex}")
    private int databaseIndex;

    @Value("${redis.cache.maxIdle}")
    private int maxIdle;

    @Value("${redis.cache.minIdle}")
    private int minIdle;

    @Value("${redis.cache.testOnBorrow}")
    private Boolean testOnBorrow;

    @Value("${redis.cache.testOnReturn}")
    private Boolean testOnReturn;

    @Value("${redis.cache.testWhileIdle}")
    private Boolean testWhileIdle;


    @Value("${redis.cache.maxWaitMillis}")
    private int maxWaitMillis;

    @Bean
    public JedisPool redisPoolFactory() {
        //該代碼就是將原先就項目xml設置的內容
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnReturn(testOnReturn);
        jedisPoolConfig.setTestWhileIdle(testWhileIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password, databaseIndex);
        logger.info("JedisPool注入成功!");
        logger.info("redis地址:" + host + ":" + port);
        return jedisPool;
    }
}

在此就將Jedis注入Spring,僅需在 RedisClient.java 中的 JedisPool 屬性添加註入,即可使用

private static final Logger logger = Logger.getLogger(RedisClient.class);

    //添加此註解進行注入,可刪除該屬性get set 方法
	@Autowired
	private JedisPool jedisPool;

	private ObjectMapper mapper;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章