建立SpringBoot项目,连接Redis进行操作
1、pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2、application.yml
spring:
redis:
host: 192.168.0.106
password: 123456
database:2
3、UserEntity.java
@Data
public class UserEntityimplements Serializable {
private LonguserId;
private StringuserName;
}
4、RedisTemplateUtils.java
@Component
public class RedisTemplateUtils {
@Resource
private RedisTemplateredisTemplate;
public void set(K k,V v){
set(k, v,null);
}
public void set(K k,V v, Long timeout){
redisTemplate.opsForValue().set(k, v);
if(timeout !=null){
redisTemplate.expire(k, timeout, TimeUnit.SECONDS);
}
}
public V get(K k){
return redisTemplate.opsForValue().get(k);
}
}
5、IndexController.java
@RestController
public class IndexController {
@Autowired
private RedisTemplateUtilsredisTemplateUtils;
@RequestMapping("/set")
public void set(UserEntity userEntity) {
redisTemplateUtils.set("user1", userEntity);
}
@RequestMapping("/get")
public UserEntity get() {
UserEntity userEntity =redisTemplateUtils.get("user1");
return userEntity;
}
}
redis存储对象可以使用json,也可以使用RedisTemplate模板直接存储,相对来说使用RedisTemplate模板操作更方便如上面的实例。