org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-test
test
2.application.yaml配置redis
redis:
host: 127.0.0.1
port: 6379
#有密码的要这个没有密码不用写
#password:
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 500
# 连接池中的最小空闲连接
min-idle: 0
lettuce:
#在关闭客户端连接之前等待任务处理完成的最长时间,在这之后,无论任务是否执行完成,都会被执行器关闭。断开与客户端的链接,防止资源不释放
#默认就是100ms
shutdown-timeout: 100
3.设置序列化
1.为啥要使用序列化?
在JAVA中,一切皆对象,而将对象的状态信息转为存储或传输的形式需要序列化。
当我们不配置序列化时候使用@AutoWired注解IOC容器为我们选择了StringRedisTemplate类来注入
package com.zrp.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
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.GenericToStringSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate
4.添加代码测试
import com.zrp.DomeApplication;
import com.zrp.po.User;
import javafx.application.Application;
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.data.redis.serializer.RedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DomeApplication.class)
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testRedis1(){
redisTemplate.opsForValue().set("aa","123");
redisTemplate.opsForValue().set("aa","123", 10,TimeUnit.SECONDS);
System.out.println( redisTemplate.opsForValue().get("aa"));
User u = new User();
u.setAge(14);
u.setUserId(123);
redisTemplate.opsForValue().set("bb",u);
System.out.println(redisTemplate.opsForValue().get("bb"));
}
@Test
public void testRedis2(){
//或者
//redisTemplate.setKeySerializer(new StringRedisSerializer());
//redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set("myKey","myValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
}



