Spring Boot - Redis pipline
By:Roy.LiuLast updated:2021-02-03
This article shows how to use Reids pipline in Spring Boot.
1. Maven dependency
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-redis</ artifactId > </ dependency > |
2. RedisServie.java
@Service public class RedisService { private RedisTemplate redisTemplate; @SuppressWarnings ({ "unchecked" , "rawtypes" }) @Autowired (required = false ) public void setRedisTemplate(RedisTemplate redisTemplate) { RedisSerializer<String> stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setValueSerializer( new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setHashValueSerializer( new GenericJackson2JsonRedisSerializer()); this .redisTemplate = redisTemplate; } public void piplineBatchSet(Map<String, String> map, Long seconds) { redisTemplate.executePipelined( new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { map.forEach((key,value)->{ connection.set(redisTemplate.getStringSerializer().serialize(key), redisTemplate.getStringSerializer().serialize(value), Expiration.seconds(seconds), RedisStringCommands.SetOption.UPSERT); }); return null ; }; } ); } |
3. TestController.java
@RestController public class TestController { @Autowired private RedisService redisService; @RequestMapping ( "/redis/pipline" ) public String redisPipline() { long beginTime = System.currentTimeMillis(); Map<String, String> map = new HashMap<>(); for ( int i= 0 ; i< 100000 ; i++) { map.put( "key" + i, "value:" + i); if (i % 1000 == 0 ) { redisService.piplineBatchSet(map, 120L); map.clear(); } } long endTime = System.currentTimeMillis(); System.out.println( "total cost: " + (endTime-beginTime)); return "OK" ; } } |
From:Is Everything OK
Previous:Using shell to backup mysql database
COMMENTS