引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
配置文件
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123456
源码
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
/**
* (User)表服务实现类
*/
@Service("userService")
public class UserServiceImpl implements UserService {
private static final String KEY = "user";
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 新增数据
*
* @param user 实例对象
* @return 实例对象
*/
@Override
public Map<String, Object> insert(User user) {
HashOperations<String, String, Object> hashOperations = this.stringRedisTemplate.opsForHash();
hashOperations.put(KEY, "id", UUID.randomUUID().toString());
hashOperations.put(KEY, "name", user.name);
hashOperations.put(KEY, "gender", user.gender.toString());
hashOperations.put(KEY, "height", user.height.toString());
hashOperations.put(KEY, "weight", user.weight.toString());
hashOperations.put(KEY, "country", user.country);
hashOperations.put(KEY, "createTime", new Date().toString());
Set<String> keys = hashOperations.keys(KEY);
Map<String, Object> map = new HashMap<>();
for (String key : keys) {
map.put(key, hashOperations.get(KEY, key));
}
return map;
}
}
还没有评论,来说两句吧...