springboot入门_data_redis
本文记录在springboot项目中使用redis存储数据。
在项目中引入需要的jar包
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-web</artifactId> 8 </dependency> 9 <dependency> 10 <groupId>org.springframework.boot</groupId> 11 <artifactId>spring-boot-starter-test</artifactId> 12 <scope>test</scope> 13 </dependency>
在属性文件application.properties中加入redis配置信息,这样我们就可以使用springboot给我们提供的RedisTemplate来访问redis
1 # redis 属性信息 2 ## redis数据库索引(默认为0) 3 spring.redis.database=0 4 ## redis服务器地址 5 spring.redis.host=localhost 6 ## redis服务器连接端口 7 spring.redis.port=6379 8 ## redis服务器连接密码(默认为空) 9 spring.redis.password= 10 ## 连接池最大连接数(使用负值表示没有限制) 11 spring.redis.jedis.pool.max-active=8 12 ## 连接池中的最大空闲连接 13 spring.redis.jedis.pool.max-idle=8 14 ## 连接池最大阻塞等待时间(使用负值表示没有限制) 15 spring.redis.jedis.pool.max-wait=-1ms 16 ## 连接池中的最小空闲连接 17 spring.redis.jedis.pool.min-idle=0
创建一个要操作的实体对象
1 public class City implements Serializable { 2 private static final long serialVersionUID = 9027850373102177538L; 3 4 private Integer id; 5 private String citeCode; 6 private String cityName; 7 8 public City() {} 9 10 public City(Integer id, String citeCode, String cityName) { 11 this.id = id; 12 this.citeCode = citeCode; 13 this.cityName = cityName; 14 } 15 16 @Override 17 public String toString() { 18 return "City{" + 19 "id=" + id + 20 ", citeCode='" + citeCode + '\'' + 21 ", cityName='" + cityName + '\'' + 22 '}'; 23 } 24 25 //省略get和set方法 26 }
测试
1 @RunWith(SpringRunner.class) 2 @SpringBootTest 3 public class SpringbootDataRedisApplicationTests { 4 5 @Autowired 6 private RedisTemplate redisTemplate; 7 8 @Test 9 public void testSet(){ 10 redisTemplate.opsForValue().set("cityInfoStr", new City(1, "BJ", "北京").toString()); 11 System.out.println("获取字符串值:"+redisTemplate.opsForValue().get("cityInfoStr")); 12 List<City> list = Collections.synchronizedList(new ArrayList<City>()); 13 list.add(new City(1,"BJ","beijing")); 14 list.add(new City(2,"SH","shanghai")); 15 redisTemplate.opsForList().leftPush("cityList", list); 16 System.out.println("获取集合值:"+redisTemplate.opsForList().index("cityList",1)); 17 18 List<City> list1 = Collections.synchronizedList(new ArrayList<City>()); 19 list1.add(new City(1,"WH","wuhan")); 20 list1.add(new City(2,"XA","xian")); 21 redisTemplate.opsForList().rightPush("cityList", list1); 22 System.out.println("获取集合值:"+redisTemplate.opsForList().index("cityList",2)); 23 } 24 25 }
需要注意opsFor...的操作对象不一样:
opsForValue:操作字符串对象
opsForList:操作list对象
opsForHash:操作hash对象
opsForSet:操作Set对象
opsForZset:操作有序的Set对象
所以我们在保存相关对象时需要用相应的方法。