Redis 缓存示例

接口

public interface RedisInterface {

    String get(String key);

    void set(String key, String value);

}

实现类

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MapRedisImpl implements RedisInterface {

    private final RedissonClient redissonClient;

    @Override
    public String get(String key) {
        return (String) redissonClient.getBucket(key).get();
    }

    @Override
    public void set(String key, String value) {
        redissonClient.getBucket(key).set(value);
    }
}

Cache

@Data
public class Cache {
    public Integer a;
    public Double d;
    public Long l;
    ......
}

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ConfigCache {

    private final RedisInterface redisInterface;
    

    public Cache mapMatchingConfig(String buildId) {
        String key = "map.matching.config-" + buildId;
        String config = redisInterface.get(key);
        if (config != null) {
            return JsonUtil.fromJson(config, MapMatchingConfig.class);
        }

        // 
        else {
            Cache cache = new Cache();
            cache.set(...);
            redisInterface.set(key, JsonUtil.toJson(cache));
        }
        .....
    }
}

 

你可能感兴趣的:(Redis 缓存示例)