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的使用
相关推荐
springboot集成redis集群以及单点(lettuce) 依赖 <groupId>org.springframework.boot <artifactId>spring-boot-starter-data-redis <groupId>org.apache.commons <artifactId>commons-pool2 </dependency>
spring-boot-examples-master示例程序,与各种框架集成,包括: dockercompose-springboot-mysql-nginx spring-boot-actuator spring-boot-banner spring-boot-docker spring-boot-elasticsearch spring-boot-...
- [spring-boot-redis](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-redis):Spring Boot 集成 Redis 示例 - [spring-boot-jpa]...
spring boot 集成 redis 的例子
spring boot demo 是一个Spring Boot、Spring Cloud的项目示例,根据市场主流的后端技术,共集成了30+个demo,未来将持续更新。该项目包含helloworld(快速入门)、web(ssh项目快速搭建)、aop(切面编程)、data-redis...
springboot2集成redis,下载后加压项目,是用idea编辑器,修改redis.yml文件修改自己的redis连接地址即可,运行demo在RedisTest 文件中
redis集成 mybatis缓存实现和redis session共享问题,详细代码。 结合项目中优点: (1) 因为数据存在内存中,类似于 HashMap ,HashMap 的优势就是查找和操作的时间复杂度都是O (1) 。 (2) Redis 本质上是一个 Key-...
spring boot 集成redis代码
小伙伴们在学习的过程中大概也发现了这两个框架...OK,由于这些已经存在的问题,Spring Boot应运而生,使用Spring Boot可以让我们快速创建一个基于Spring的项目,而让这个Spring项目跑起来我们只需要很少的配置就可以了
Spring Boot框架集成Redis教程
spring-boot骨架工程,集成了mysql,mybatis,redis,swagger
spring-boot-plus集成Spring Boot 2.1.6,Mybatis,Mybatis Plus,Druid,FastJson,Redis,Rabbit MQ,Kafka等,可使用代码生成器快速开发项目
springboot,mybatis,redis缓存 集成
简介该项目主要利用Spring Boot的自动化配置特性来实现快速的将Shiro集成到SpringBoot应用...增加11种过滤器过滤规则配置功能默认使用开源库org.crazycake:shiro-redis:3.2.2集成redis增加shiro的redis独立配置功能,可
springboot整合redis集群(三种方式)源码
springBoot+mybatis+redis集成,不上代码要确保redis服务端已经运行
spring-boot最佳实践spring-boot工程学习,按模块划分工程结构,spring-boot集成每一个小的功能都单独拿出一个工程,保证每个工程都能独立运行。spring-boot脚手架地址每个模块的详细介绍在工程下的README.md文件里...
springboot集成redis ————使用Spring Data Redis的方式,简单的使用opsForValue的方式来进行完整的增删改查功能,包括数据库,直接导入便可使用
主要介绍了详解Spring-Boot集成Spring session并存入redis,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Spring boot 集成 redis (解决String类型乱码) 缓存用redis