spring-boot集成redis
程序员文章站
2022-06-22 16:07:16
...
1、pom.xml文件中添加redis依赖
<!-- Spring Boot redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
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<T> { /** * 实例化stringRedisTemplate * @param factory * @return */ @Bean public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); return template; } /** * 实例化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、添加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<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(); } /** * 递增操作 * * @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("lihua_java@163.com"); 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> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> 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的使用