下面讲解下windows上面redis的安装与使用,以及在springboot环境下,怎么使用API来快速上手redis。Redis官方是没有提供Windows版本的,因为目前Linux版本已经相当稳定,而且用户量很大,无需开发windows版本,反而会带来兼容性等问题。
windows上面redis的安装与使用
启动服务器之后的场景
在客户端对redis进行操作
redis在springboot程序中的使用
导入依赖
<!-- redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- SpringBootTest-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!-- <scope>test</scope>-->
</dependency>
Java配置
package cn.wideth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
/**
* 编写配置类,构造RedisTemplate
* 这个springboot已经帮我们配了,
* 但是默认object,我想改成string
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 设置key的序列化方式
template.setKeySerializer(RedisSerializer.string());
// 设置value的序列化方式
template.setValueSerializer(RedisSerializer.json());
// 设置hash的key的序列化方式
template.setHashKeySerializer(RedisSerializer.string());
// 设置hash的value的序列化方式
template.setHashValueSerializer(RedisSerializer.json());
template.afterPropertiesSet();
return template;
}
}
在程序中调用相关的API来进行程序操作
package cn.wideth.util.other;
import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class TestRedis {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void operateStr(){
System.out.println(redisTemplate);
// 存入key为hello ,value为world
redisTemplate.opsForValue().set("hello","world");
// 获取key为hello
String username = (String) redisTemplate.opsForValue().get("hello");
System.out.println(username);
}
}
程序结果