@TedZhou
2020-06-28T14:01:04.000000Z
字数 2528
阅读 642
spring
boot
redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
#spring.data.redis.repositories.enabled=false
spring.cache.type=redis
# 用redis存储session
spring.session.store-type=redis
spring.session.redis.namespace=myproject:session
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在类和方法分别用@CacheConfig和@Cacheable、@CachePut、@CacheEvict等注解即可。
@Service
@CacheConfig(cacheNames = "myprojectcache:somentity")
public class SomentityService {
@Cacheable(key="#id")
public Somentity findById(Integer id) {
//TODO:
}
}
如果注解方式不能满足要求,可以注入@Resource cacheManager调用其方法处理缓存。
@Resource private CacheManager cacheManager;
//获取cache
cacheManager.getCache("myprojectcache:somentity").get/put/evict(...);
@Configuration
public class RedisConfig {
@Bean
public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
@Component
public interface RedisMessageHandler {
public void handleMessage(String message);
}
@Slf4j
public class MyMessageHandler implements RedisMessageHandler {
@Override
public void handleMessage(String text) {
log.debug(text);
}
}
@Autowired RedisMessageListenerContainer messageListenerContainer;
@Synchronized public void addMessageListener(String channel) {
if (!exists(channel) {
MessageListenerAdapter listener = new MessageListenerAdapter(new MyMessageHandler(channel));
listener.afterPropertiesSet();
messageListenerContainer.addMessageListener(listener, new ChannelTopic(channel));
}
}
@Autowired private StringRedisTemplate stringRedisTemplate;
public void sendMsg(String channel, String message){
stringRedisTemplate.convertAndSend(channel, message);
}
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
Long value = ops.increment(key) : ops.decrement(key);
Set<String> keys = stringRedisTemplate.keys(keyPrefix);
List<String> values = ops.multiGet(keys);
stringRedisTemplate.delete(key);
stringRedisTemplate.remame(key, newkey);