import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
 
import java.util.Collections;
 
@Service
public class RedisPipelineService {
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    public void batchIncrement(String keyPrefix, int start, int end) {
        // 确保在pipeline中使用的key有相同的前缀
        String[] keys = new String[end - start + 1];
        for (int i = start; i <= end; i++) {
            keys[i - start] = keyPrefix + i;
        }
 
        // 使用Lua脚本保证原子性
        String luaScript = 
            "for i = 1, #KEYS do " +
            "   redis.call('INCR', KEYS[i]) " +
            "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(luaScript);
        redisScript.setResultType(Long.class);
 
        // 执行pipeline批量操作
        redisTemplate.executePipelined((pipeline) -> {
            for (String key : keys) {
                pipeline.opsForValue().increment(key); // 自增操作
            }
            pipeline.script().eval(redisScript, Collections.singletonList(keyPrefix + "counter"), keys); // 使用Lua脚本批量自增
        });
    }
}这段代码演示了如何在Spring Boot应用中使用StringRedisTemplate来执行一个pipeline操作,该操作将一系列键自增,并使用Lua脚本保证操作的原子性。这是一个简化的例子,实际应用中可能需要更复杂的逻辑处理。