spring-boot integrates redis

 

1. Add redis dependency to pom.xml file

		<!-- Spring Boot redis dependencies -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

 

2, application.yml placed in redis

spring:
  say again:
    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
      
# say again:
#    cluster:
#      nodes:
#      - 172.16.90.30:7000
#      - 172.16.90.30:7001

 

3. Instantiate 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<T> {
	
	/**
	 * Instantiate stringRedisTemplate
	 * @param factory
	 * @return
	 */
	@Bean
	public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory factory) {
		 StringRedisTemplate template = new StringRedisTemplate(factory);
		 return template;
	}

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

 

4. Add redis tool class

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 tool class
 * @author lh
 * @version 1.0
 * @since 2017-12-27
 *
 */
public class RedisUtils {
	
	private static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate");
	private static RedisTemplate<String, Object> 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> T get(String key, Class<T> 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();
	}
	
	/**
	 * Increment operation
	 *
	 * @param key
	 * @param by
	 * @return
	 */
	public static double incr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, by);
	}
	
	/**
	 * Decrement operation
	 *
	 * @param key
	 * @param by
	 * @return
	 */
	public static double decr(String key, double by) {
		return stringRedisTemplate.opsForValue().increment(key, -by);
	}

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

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

	
}

 

5. Test the RedisUtils tool class

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. Other categories

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;

/**
 * Save the Spring ApplicationContext as a static variable, you can retrieve the ApplicaitonContext at any time in any code.
 *
 * @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);

	/**
	 * Get the ApplicationContext stored in a static variable.
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 * Get the Bean from the static variable applicationContext and automatically convert it to the type of the assigned object.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	/**
	 * Get the Bean from the static variable applicationContext and automatically convert it to the type of the assigned object.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}

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

	/**
	 * Implement the ApplicationContextAware interface, inject Context into static variables.
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		LOGGER.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
		if (SpringContextHolder.applicationContext != null) {
			LOGGER.info("The ApplicationContext in SpringContextHolder is overwritten, the original ApplicationContext is: {}" , SpringContextHolder.applicationContext);
		}
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * Implement the DisposableBean interface to clean up static variables when the Context is closed.
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}

	/**
	 * Check that ApplicationContext is not empty.
	 */
	private static void assertContextInjected() {
		if(applicationContext == null) {
			throw new InstantiationError("applicaitonContext property is not injected, please define SpringContextHolder in applicationContext.xml.");
		}
		//Validate.validState(applicationContext != null, "applicaitonContext property is not injected, please define SpringContextHolder in applicationContext.xml.");
	}
}

 

 Reference blog: The use of Redis in Spring Boot

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326201181&siteId=291194637