1.导入spring-data-redis jar包:https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis
导入 jedis jar包:https://mvnrepository.com/artifact/redis.clients/jedis
注意jar包的版本问题:推荐如下两个jar包:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
2.在spring的xml中配置:
<!-- usePool属性:是否启动连接池 -->
<bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:usePool="true" p:password="ps123456" p:hostName="192.168.0.243" p:port="6379"/>
<!-- spring中操作redis的类 -->
<bean id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory" />
3.配完之后,在做一个测试:在网页上打出redis中一个string类型的值:
测试类:
@Autowired
private RedisTemplate<String, String> redis;
// 设置存值的key及value不出现乱码
public RedisTemplate<String, String> redisTemplateInit() {
//设置序列化Key的实例化对象
redis.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redis.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redis;
}
@ResponseBody // 返回一个json对象
@RequestMapping("/set")
public void testSet() {
BoundValueOperations<String, String> boundValueOps = redisTemplateInit().boundValueOps("names");
boundValueOps.set("我是一个好人");
}
@ResponseBody // 返回一个json对象
@RequestMapping(value="/get",produces = "text/html;charset=GBK")
public String testGet() throws UnsupportedEncodingException {
/*BoundValueOperations<String, String> boundValueOps = redis.boundValueOps("name");
boundValueOps.set("hello");*/
String string = redisTemplateInit().boundValueOps("names").get().toString();
System.out.println(string);
return string;
}
效果如下: