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;

 

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