<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
application.properties
spring.redis.host=localhost
spring.redis.port=6379
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class RedisExample {
private final RedisTemplate<String, String> redisTemplate;
private final ObjectMapper objectMapper;
public RedisExample(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
this.objectMapper = new ObjectMapper();
}
public void storeData(Map<String, Map<String, Action>> outerMap) {
try {
String jsonData = objectMapper.writeValueAsString(outerMap);
ValueOperations<String, String> ops = redisTemplate.opsForValue();
ops.set("complexMap", jsonData);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public Map<String, Map<String, Action>> retrieveData() {
try {
ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
String jsonData = ops.get("complexMap");
return objectMapper.readValue(jsonData, new TypeReference<>() {});
} catch (IOException e) {
e.printStackTrace();
return new HashMap<>();
}
}
public void updateAction(String key, String actionKey, Action newAction) {
Map<String, Map<String, Action>> outerMap = retrieveData();
if (outerMap.containsKey(key) && outerMap.get(key).containsKey(actionKey)) {
outerMap.get(key).put(actionKey, newAction);
storeData(outerMap);
}
}
}
import java.io.Serializable;
public class Action implements Serializable {
private String name;
private String description;
}