Spring-boot統合redis

10458 ワード

詳細
 
1、pom.xmlファイルにredis依存性を追加
		
		
			org.springframework.boot
			spring-boot-starter-data-redis
		

 
2、application.ymlでredisを構成する
spring: 
  redis:
    database: 0
    host: 172.16.90.30
    port: 6379
    password: redis
    timeout: 0
    pool:
      max-active: 8
      max-wait: -1
      max-idle: 8
      min-idle: 0
      
#  redis:
#    cluster:
#      nodes:
#      - 172.16.90.30:7000
#      - 172.16.90.30:7001

 
3、実例化redisTemplate
package com.huatech.supports;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
	
	/**
	 *    stringRedisTemplate
	 * @param factory
	 * @return
	 */
	@Bean
	public RedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
		 StringRedisTemplate template = new StringRedisTemplate(factory);
		 return template;
	}

	/**
	 *    RedisTemplate
	 * 
	 * @param factory
	 * @return
	 */
	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate template = new RedisTemplate();
		template.setConnectionFactory(factory);
		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		template.afterPropertiesSet();
		return template;
	}	
}

 
4、redisツールクラスの追加
package com.huatech.util;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.huatech.supports.SpringContextHolder;
/**
 * Redis   
 * @author lh
 * @version 1.0
 * @since 2017-12-27
 *
 */
public class RedisUtils {
	
	private static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate");
	private static RedisTemplate redisTemplate = SpringContextHolder.getBean("redisTemplate");
	
	public static void set(String key, String value, long timeout) {
		stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
	}
	
	public static void set(String key, Object value, long timeout) {
		if (value instanceof String) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value instanceof Integer || value instanceof Long) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value instanceof Double || value instanceof Float) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value instanceof Short || value instanceof Boolean) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else {
			redisTemplate.opsForValue().set(key, value);
		}
		if(timeout > 0) {
			expire(key, timeout);
		}
	}
	
	public static boolean setnx(String key, Object value) {
		return redisTemplate.opsForValue().setIfAbsent(key, value);
	}
	
	public static void del(String key) {
		redisTemplate.delete(key);
	}
	
	public static void expire(String key, long timeout) {
		redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
	}
	
	public static boolean exists(String key) {
		return redisTemplate.hasKey(key);
	}
	
	public static String get(String key) {
		return stringRedisTemplate.boundValueOps(key).get();
	}
	
	@SuppressWarnings("unchecked")
	public static  T get(String key, Class clazz) {
		if (clazz.equals(String.class)) {
			return (T) stringRedisTemplate.boundValueOps(key).get();
		} else if (clazz.equals(Integer.class) || clazz.equals(Long.class)) {
			return (T) stringRedisTemplate.boundValueOps(key).get();
		} else if (clazz.equals(Double.class) || clazz.equals(Float.class)) {
			return (T) stringRedisTemplate.boundValueOps(key).get();
		} else if (clazz.equals(Short.class) || clazz.equals(Boolean.class)) {
			return (T) stringRedisTemplate.boundValueOps(key).get();
		}
		return (T) redisTemplate.boundValueOps(key).get();
	}
	
	/**
	 *     
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static double incr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, by);
	}
	
	/**
	 *     
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static double decr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, -by);
	}

	/**
	 *     
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static long incr(String key, long by) {
		return stringRedisTemplate.opsForValue().increment(key, by);
	}

	/**
	 *     
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public static long decr(String key, long by) {
		return stringRedisTemplate.opsForValue().increment(key, -by);
	}

	
}

 
5.RedisUtilsツールクラスのテスト
package com.huatech;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.huatech.domain.User;
import com.huatech.util.RedisUtils;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisUtilsTest {
	
	
	@Test
	public void testRedis()throws Exception{
		String key = "spring:boot:user";
		User user = new User();
		user.setId(21L);
		user.setCreateTime(new Date());
		user.setUsername("lihua");
		user.setEmail("[email protected]");
		System.out.println(user);
		RedisUtils.set(key, user, 1);
		System.out.println(RedisUtils.get(key, User.class));
		Thread.sleep(1500L);
		System.out.println(RedisUtils.get(key, User.class));
		
	}
	
}

 
6、その他のクラス
package com.huatech.supports;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 *        Spring ApplicationContext,                 ApplicaitonContext.
 * 
 * @author lh
 * @date 2017-12-27
 */
@Component
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext applicationContext = null;

	private static final Logger LOGGER = LoggerFactory.getLogger(SpringContextHolder.class);

	/**
	 *            ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 *      applicationContext   Bean,              .
	 */
	@SuppressWarnings("unchecked")
	public static  T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	/**
	 *      applicationContext   Bean,              .
	 */
	public static  T getBean(Class requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}

	/**
	 *   SpringContextHolder  ApplicationContext Null.
	 */
	public static void clearHolder() {
		LOGGER.debug("  SpringContextHolder  ApplicationContext:{}" , applicationContext);
		applicationContext = null;
	}

	/**
	 *   ApplicationContextAware  ,   Context      .
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		LOGGER.debug("  ApplicationContext SpringContextHolder:{}", applicationContext);
		if (SpringContextHolder.applicationContext != null) {
			LOGGER.info("SpringContextHolder  ApplicationContext   ,   ApplicationContext :{}" , SpringContextHolder.applicationContext);
		}
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 *   DisposableBean  ,  Context         .
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}

	/**
	 *   ApplicationContext   .
	 */
	private static void assertContextInjected() {
		if(applicationContext == null) {
			throw new InstantiationError("applicaitonContext     ,   applicationContext.xml   SpringContextHolder.");
		}
		//Validate.validState(applicationContext != null, "applicaitonContext     ,   applicationContext.xml   SpringContextHolder.");
	}
}

 
参考ブログ:Spring BootでのRedisの使用