springboot整合redis

springboot整合redis

概述

这篇文章主要是根据springboot官方给出的demo做的一个springboot整合redis的一个入门级别的博客。
springboot整合redis需要了解的知识点:
1. springboot的基本了解,包括常用注解、依赖、配置文件
2. redis的基本了解,最起码需要知道redis的如何安装及安全设置
3. spring data redis的基本了解,springboot整合redis实际上是对此做了一些封装。

步骤

  • 依赖添加
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
</dependency>
  • 配置文件application.yml编写
spring:
  redis:
    host: 192.168.44.129
    password: admin
  session:
    store-type: none

注意:redis安装成功后,默认密码为空。所以需要先配置一个redis的密码,否则可能会出现问题以下问题:http://blog.csdn.net/mynameissls/article/details/73130989

  • 测试启动类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void run(String... args) throws Exception {
        ValueOperations<String, String> ops = this.template.opsForValue();
        String key = "spring.boot.redis.test";
        if (!this.template.hasKey(key)) {
            ops.set(key, "foo");
        }
        System.out.println("Found key " + key + ", value=" + ops.get(key));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

运行完测试启动类后,可以去redis的服务器上查看是否存在key=spring.boot.redis.test的一个数据,如下:

[root@localhost src]# ./redis-cli 
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> get spring.boot.redis.test
"foo"
127.0.0.1:6379>

参考链接:https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
源代码链接:https://github.com/myNameIssls/springboot-study

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值