spring boot的出现,大大加快了开发的步骤,在一些数据库的操作上 xxxTemplate使用非常的方便
今天来测试一下.spring boot 的对redis 的操作,使用redisTemplate
首先用maven 新建一个spring boot 的web工程
在pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
或者是
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
两个二选一,都是可以的
3.配置application.properties文件
redisTemplate比较方便的是它既支持redis单机模式,还支持redis集群模式,仅仅是吧配置文件改一下就好了,代码不需要发生变化.
首先来看一下单机版本的在application.properties 中的配置
spring.redis.database=5
spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.port=6379
再来看下集群模式的配置
spring.redis.cluster.nodes=192.168.100.11:5657,192.168.100.12:5658,192.168.100.15:5659
spring.redis.password=
下面就是代码了,先上工具类
package com.example.redis.redisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class Myredis {
@Resource
private RedisTemplate redisTemplate;
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate redisTemplate) {
StringRedisSerializer serializer=new StringRedisSerializer();
redisTemplate.setKeySerializer(serializer);
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashKeySerializer(serializer);
redisTemplate.setHashKeySerializer(serializer);
redisTemplate.setHashValueSerializer(serializer);
this.redisTemplate = redisTemplate;
}
public void add(String key,String value){
redisTemplate.opsForValue().set(key,value);
}
}
上面的代码做了KeySerializer ,如果不做也是可以的,只是会在存储数据的时候key 和value 的前面
会多\xac\xed\x00\x05t\x00\tb 这样的东西
还有一种办法就是使用StringRedisTemplate,不过这个没有测试,大家可以试下.
下面写个Controller 接口看下
package com.example.redis.controller;
import com.example.redis.redisUtil.Myredis;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class Test {
@Resource
private Myredis myredis;
@RequestMapping("/haha")
@ResponseBody
public String aaa(){
myredis.add("aaaaaa","bbbbb");
return "ok";
}
}
然后把redis 启动起来,然后启动springboot 工程 就OK了,访问接口 就可以完成数据的添加操作