1. java操作redis方式
2. 使用jedis
添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
使用
建立连接
Jedis jedis = new Jedis("localhost",6379);
操作redis
jedis.set("name","123");
System.out.println(jedis.get("name"));
关闭连接
jedis.close();
3.使用spring data redis
导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
写yml
redis:
host: localhost
port: 6379
database: 0 # 指0号数据库
jedis:
pool:
max-active: 8 # 最大连接数
max-wait: 1ms #连接池最大阻塞等待时间
max-idle: 4 # 连接池中最大空闲链接
min-idle: 0 # 连接池宗最小空闲连接
自定义序列化器
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
// 默认为jdk序列化器,使用string序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
操作方式
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("name","张三");
String name = (String)valueOperations.get("name");
System.out.println(name);
}