资讯专栏INFORMATION COLUMN

SpringBoot非官方教程 | 第九篇: SpringBoot整合Redis

csRyan / 952人阅读

摘要:经过上述两步的操作,你可以访问数据了。数据访问层通过来访问分钟过期单元测试启动单元测试,你发现控制台打印了单元测试通过源码下载参考资料

这篇文章主要介绍springboot整合redis

引入依赖

在pom文件中添加redis依赖:


    org.springframework.boot
    spring-boot-starter-data-redis

配置数据源
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0

如果你的redis有密码,配置下即可。经过上述两步的操作,你可以访问redis数据了。

数据访问层dao

通过redisTemplate来访问redis:

@Repository
public class RedisDao {

    @Autowired
    private StringRedisTemplate template;

    public  void setKey(String key,String value){
        ValueOperations ops = template.opsForValue();
        ops.set(key,value,1, TimeUnit.MINUTES);//1分钟过期
    }

    public String getValue(String key){
        ValueOperations ops = this.template.opsForValue();
        return ops.get(key);
    }
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

    public static Logger logger= LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
    @Test
    public void contextLoads() {
    }

    @Autowired
    RedisDao redisDao;
    @Test
    public void testRedis(){
        redisDao.setKey("name","forezp");
        redisDao.setKey("age","11");
        logger.info(redisDao.getValue("name"));
        logger.info(redisDao.getValue("age"));
    }
}

启动单元测试,你发现控制台打印了:

forezp

单元测试通过;

源码下载:https://github.com/forezp/Spr...

参考资料

messaging-redis

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70374.html

相关文章

  • 一起来学SpringBoot | 九篇整合Lettuce Redis

    摘要:相比它支持存储的类型相对更多字符哈希集合有序集合列表,同时是线程安全的。基于的连接实例,可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。 SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML...

    yacheng 评论0 收藏0
  • SpringBoot官方教程 | 第十九篇: 验证表单信息

    这篇文篇主要简述如何在springboot中验证表单信息。在springmvc工程中,需要检查表单信息,表单信息验证主要通过注解的形式。 构建工程 创建一个springboot工程,由于用到了 web 、thymeleaf、validator、el,引入相应的起步依赖和依赖,代码清单如下: org.springframework.boot ...

    rottengeek 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<