springboot整合redis
@Configuration
@EnableCaching
public class RedisConfig {
@Autowired
RedisConnectionFactory connectionFactory;
@Bean(name = "redisTemplate")
public RedisTemplate<Object, Object> initRedisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
//RedisTemplate会自动初始化StringRedisSerializer,所以这里直接取
final RedisSerializer<String> stringSerializer = redisTemplate.getStringSerializer();
//设置字符串序列化器,这样spring就会吧redis的key当做字符串来处理了
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
springboot整合kafka异步发送消息
@Component
public class KafkaProducer {
private final Log log = LogFactory.getLog(KafkaProducer.class);
@Autowired
private KafkaTemplate kafkaTemplate;
@Value("${spring.kafka.template.default-topic}")
private String topic;
public void send(String key, String value) {
kafkaTemplate.sendDefault(key, value).addCallback(new ListenableFutureCallback() {
@Override
public void onSuccess(Object result) {
log.info("send to kafka sucuss");
}
@Override
public void onFailure(Throwable ex) {
if (ex != null) {
log.error("send kafka error:" + ex.getMessage());
}
}
});
}
}
spingboot提供7种数据类型操作
//获取地理位置操作接口
redisTemplate.opsForGeo();
//获取散列操作接口
redisTemplate.opsForHash();
//获取基数操作接口
redisTemplate.opsForHyperLogLog();
//获取列表操作接口
redisTemplate.opsForList();
//获取集合操作接口
redisTemplate.opsForSet();
//获取有序结合操作接口
redisTemplate.opsForZSet();
//获取字符串操作接口
redisTemplate.opsForValue();
除此以外呢,也提供了对key的连续操作7类接口
redisTemplate.boundHashOps("key");
2个回调函数SessionCallback和RedisCallback,一般是用SessionCallback
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations ro) throws DataAccessException {
ro.opsForValue().set("key1", "key2");
ro.opsForHash().put("hash", "field", "hashValue");
return null;
}
});
redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection rc) throws DataAccessException {
rc.set("key1".getBytes(), "value1".getBytes());
rc.hSet("hash".getBytes(), "field".getBytes(), "hvalue".getBytes());
return null;
}
});