SpringCloud集成Spring Data Redis
Spring Data Redis
如同使用SpringData进行关系型数据库访问一样,使用Spring Data Redis的第一步就是连接到Redis服务器。要想实现连接,就需要获取RedisConnection,而获取RedisConnection的手段是使用RedisConnectionFactory接口。Spring Data Redis对Redis操作做了封装,提供了一个工具类RedisTemplate,通过注入RedisConnectionFactory到RedisTemplate中,该RedisTemplate就能获取RedisConnection。
RedisTemplate提供了丰富的接口来操作Redis的特定数据类型,这些接口包括ValueOperations、ListOperations、SetOperations、ZSetOperations和HashOperations等,分别对应Redis中的String、List、Set、ZSet和Hash 5种常见的数据结构。
SpringCloud在集成Spring Data Redis时,需要引入spring-boot-starter-data-redis
依赖。
源码
springcloud-parent2父Maven模块
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>spring-data</module>
<module>spring-redis</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<groupId>com.lyc</groupId>
<artifactId>springcloud-parent2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>springcloud-parent2</name>
<!--导入SpringCloud的依赖管理-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
</project>
spring-redis子Maven模块
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-parent2</artifactId>
<groupId>com.lyc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-redis</artifactId>
<name>spring-redis</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
</project>
SpringRedisApplication启动类
package com.lyc.pringRedis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author: zhangzhenyi
* @date: 2019/3/10 14:34
* @description: SpringRedis启动类
**/
@SpringBootApplication
public class SpringRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisApplication.class,args);
}
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
@SuppressWarnings("unchecked")
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setKeySerializer(new StringRedisSerializer());
return template;
}
}
PersonRedisController类
package com.lyc.pringRedis.controller;
import com.lyc.pringRedis.entity.Person;
import com.lyc.pringRedis.server.PersonRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: zhangzhenyi
* @date: 2019/3/10 14:41
* @description: PersonRedis Controller
**/
@RestController
public class PersonRedisController {
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
PersonRedisRepository personRedisRepository;
/**
* 在Redis中存值
*/
@RequestMapping("/setPerson")
public void setPerson(){
Person person = Person.builder()
.id(1L)
.name("zhangsan")
.age(32)
.address("shanghai")
.build();
personRedisRepository.save(person);
}
/**
* 读取存入Redis中的值
* @return
*/
@RequestMapping("/getPerson")
public Person getPerson(){
return personRedisRepository.getPerson();
}
}
PersonRedisRepository类
package com.lyc.pringRedis.server;
import com.lyc.pringRedis.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
/**
* @author: zhangzhenyi
* @date: 2019/3/10 14:29
* @description: PersonRedis Repository
**/
@Repository
public class PersonRedisRepository {
@Autowired
RedisTemplate<Object,Object> redisTemplate;
@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "WeakerAccess"})
@Resource(name = "redisTemplate")
ValueOperations<Object,Object> valueOperations;
public void save(Person person){
valueOperations.set(person.getId().toString(),person);
}
public Person getPerson(){
return (Person) valueOperations.get("1");
}
}
Person类
package com.lyc.pringRedis.entity;
import lombok.*;
/**
* @author: zhangzhenyi
* @date: 2019/3/10 11:02
* @description: Person实体类
**/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private Long id; //主键id
private String name; //姓名
private Integer age; //年龄
private String address; //地址
}
结果
先访问:
http://localhost:8080/setPerson
再访问:
http://localhost:8080/getPerson
得到的结果如下:
该结果在Redis客户端中的访问结果如下:
分析
在Spring Data Redis中的Repository类需要注入Redis Template,并提供ValueOperations进行具体的操作,如在PersonRedisRepository类中的情况就是如此。
这里的ValueOperation依赖于RedisTemplate,而在RedisTemplate中可以对RedisConnectionFactory和序列化方式进行设置。在Spring Boot中,用于构建RedisTemplate的代码一般会放到Bootstrap类中,如上面的SpringRedisApplication就是如此。
在这里,由于我们在使用Redis时是采用的默认配置,所以说此处就没必要配置application.yml
文件了。而在默认的配置信息中,Redis服务器是以6378为端口号进行启动。