栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

19. SpringBoot集成Redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

19. SpringBoot集成Redis

SpringBoot集成Redis
  • SpringBoot集成Redis
    • 1. 添加依赖(操作Redis数据类型的依赖)
    • 2. 在SpringBoot的核心配置文件中添加Redis的配置
    • 3. 往Redis中读取、写入数据
    • 4. 程序跑起来——看结果

SpringBoot集成Redis 1. 添加依赖(操作Redis数据类型的依赖)

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

2. 在SpringBoot的核心配置文件中添加Redis的配置
#配置Redis配置信息
spring:
  redis:
    host: 192.168.0.128
    port: 6379
    password: 123456  #如果没有设置密码可以直接去掉这个属性

3. 往Redis中读取、写入数据

1.StudentController.java

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;
    @GetMapping("/put")
    public String put(String key,String value){
        studentService.put(key,value);
        return "值已经成功放入Redis";
    }
    @GetMapping("/get")
    public String get(String key){
        Object value = studentService.get(key);
        return key+"对应的Value值为:"+value;
    }
}

2.StudentService.java

package com.guo.service;

public interface StudentService {
    
    void put(String key, String value);
        
    Object get(String key);
}

3.StudentServiceImpl.java

package com.guo.service.impl;

import com.guo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {
    //引入操作Redis的模板象
    @Autowired
    private RedisTemplate redisTemplate;

    public void put(String key, String value) {
        //ops是操作
        // value就是值的是String类型的数据
        redisTemplate.opsForValue().set(key,value);
    }
    public Object get(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        return o;
    }
    
}

4. 程序跑起来——看结果
  1. 通过网址进行访问:
    http://localhost:8080/put?key=name&value=zhangsan
  2. 通过Windows上的可视化界面查看值是否成功存入
  3. 通过网址读取Redis中的数据
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号