简单了解一下
1.build.gradle中添加 依赖 org.springframework.boot:spring-boot-starter-data-redis
//定义依赖:声明项目中需要哪些依赖 dependencies { //当前模块依赖项 //compile ‘org.springframework.boot:spring-boot-starter‘ //testCompile ‘org.springframework.boot:spring-boot-starter-test‘ compile ‘org.springframework.boot:spring-boot-starter-actuator‘ compile ‘org.springframework.boot:spring-boot-starter-web‘ compile ‘org.springframework.boot:spring-boot-starter-data-redis‘ testCompile group:‘junit‘,name:‘junit‘,version:‘4.12‘
2.application.properties中添加 redis的配置
#Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0
3.程序入库处配置允许缓存 @EnableCaching
@SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4.简单写入读取:
@RestController public class TestController { @Autowired private StringRedisTemplate stringRedisTemplate=new StringRedisTemplate(); @RequestMapping(value = "/getinfo") public String getInfo(){ stringRedisTemplate.opsForValue().set("name","二庄"); stringRedisTemplate.opsForValue().set("age","18"); System.out.println("***姓名:"+stringRedisTemplate.opsForValue().get("name")+" 年龄:"+stringRedisTemplate.opsForValue().get("age")); String result=String.format("***姓名:"+stringRedisTemplate.opsForValue().get("name")+" 年龄:"+stringRedisTemplate.opsForValue().get("age")); return result; }
中途遇到的问题:
问题1:存入redis的数据有中文,显示的是中文对应的Unicode编码
在启动redis-cli时在其后面加上--raw参数即可启动后 ,此时Unicode编码变成乱码了。
然后打开cmd的属性,设置字体为 Lucida Console,问题解决!
问题2: 使用 stringRedisTemplate.opsForValue().set("name","二庄"); 报错 :template not initialized; call afterPropertiesSet() before using it
原因: 没加@Autowired
@Autowired
private StringRedisTemplate stringRedisTemplate=new StringRedisTemplate();
原文:https://www.cnblogs.com/jerrys/p/10901368.html