趁着今天休息就学习了一下redis,刚开始配置的时候遇到一些坑,现在写下来记一下,首先springboot使用的版本是2.X(我使用的是2.1.6)我的是在本地配置的,环境是windows环境,首先要先安装redis
- 安装redis windows下载链接:https://github.com/MicrosoftArchive/redis/releases
- 解压到指定目录即可
- 进入redis的安装目录启动redis:redis-server redis.windows.conf 启动成功
- 首先在pom.xml中添加相应依赖
<!-- 2.* 版本 redis依赖改名了,直接使用下面的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置application.properties文件
# Redis数据库分片索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host= 192.168.196.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
3.新建类Rediscontroller
package com.example.ribbonclient.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RedisController {
@Autowired
RedisTemplate redisTemplate;
@RequestMapping("/set")
public String setHello(String key,String value){
redisTemplate.opsForValue().set(key,value);
return "redis success";
}
@RequestMapping("/get")
public String getHello(String key){
String value = (String)redisTemplate.opsForValue().get(key);
return "redis value=" + value;
}
}
4.访问http://localhost:1011/set?key=name&value=zwr
5.得到刚才设置的值http://localhost:1011/get?key=name