springboot整合Redis
前言
Redis是目前使用的非常廣泛的記憶體資料庫,相比memcached,它支援更加豐富的資料類型。本來簡要介紹在springboot中使用redis的方法。 如何使用。
1、引入spring-boot-starter-redis
<!-- redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2、在application.properties增加Redis的配置
# 使用的資料庫(0-15),預設為0spring.redis.database=0 # Redis伺服器位址spring.redis.host=127.0.0.1# Redis伺服器串連連接埠spring.redis.port=6379 # Redis伺服器串連密碼(預設為空白)spring.redis.password=
3、使用
@Autowiredprivate StringRedisTemplate stringRedisTemplate;@RequestMapping(value = "/redis/{key}/{value}",method = RequestMethod.GET)@ResponseBodypublic String redisTest(@PathVariable String key,@PathVariable String value) { String redisValue = stringRedisTemplate.opsForValue().get(key); if (StringUtils.isEmpty(redisValue)) { stringRedisTemplate.opsForValue().set(key,value); return "操作成功。"; } if (!redisValue.equals(value)) { stringRedisTemplate.opsForValue().set(key,value); return "操作成功。"; } return String.format("redis中已存在[key=%s,value=%s]的資料。",key,value);}
隨便寫的一個例子。
4、Sentinel模式配置
上面的是單機的一個配置,如果是主從,參考:
#redis配置spring.redis.database=0spring.redis.password=systemspring.redis.pool.max-idle=10spring.redis.pool.min-idle=0spring.redis.pool.max-active=10spring.redis.pool.max-wait=-1spring.redis.sentinel.master=mymasterspring.redis.sentinel.nodes=192.168.74.135:26379,192.168.74.136:26379
5、redis的全部配置:
# REDIS (RedisProperties)spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.spring.redis.database=0 # Database index used by the connection factory.spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379spring.redis.host=localhost # Redis server host.spring.redis.password= # Login password of the redis server.spring.redis.ssl=false # Enable SSL support.spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.spring.redis.port=6379 # Redis server port.spring.redis.sentinel.master= # Name of Redis server.spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.spring.redis.timeout=0 # Connection timeout in milliseconds.
6、使用redis自動快取資料
可以把一些經常查詢的資料放到redis緩衝起來,不用每次都查詢資料庫。
上面是手動快取到redis,這裡介紹一下如何自動資料緩衝到redis。
a.增加一個redis的配置類:
@Configuration@EnableCachingpublic class RedisConfig{ @Bean public KeyGenerator redisKeyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @Bean public CacheManager cacheManager( @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); } @Bean public RedisTemplate<String, String> redisTemplate( RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }}
b.在需要緩衝的service方法上加上註解:
@Cacheable(value = "userCache")public TUser findById(String id) { return this.userRepository.findOne(id);}
這樣,就只有redis沒有相應的Key的時候才會查詢資料庫。
我們看下redis:
圖中,redis的key就是你的參數。