参考文章:https://blog.csdn.net/m0_38075425/article/details/81181726
https://blog.csdn.net/stronglyh/article/details/81173563
https://blog.csdn.net/qq_38157516/article/details/82356902
<!--spring2.0集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties配置文件:
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.jedis.pool.max-wait=8
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
## 连接超时时间(毫秒)
#spring.redis.timeout=5000
package com.xx.zonghe.config;
import java.io.Serializable;
import java.util.concurrent.CountDownLatch;
import com.shengquan.zonghe.utils.ObjectRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置
* @author pangjianhui
*
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Serializable, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Serializable, Object> template = new RedisTemplate<Serializable, Object>();
template.setConnectionFactory(connectionFactory);
template.afterPropertiesSet();
// redis存取对象的关键配置
template.setKeySerializer(new StringRedisSerializer());
// ObjectRedisSerializer类为java对象的序列化和反序列化工具类
template.setValueSerializer(new ObjectRedisSerializer());
return template;
}
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
@Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
}
@Bean
CountDownLatch latch() {
return new CountDownLatch(1);
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
public class Receiver {
private CountDownLatch latch;
@Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
}
public void receiveMessage(String message) {
latch.countDown();
}
}
}
package com.xx.zonghe.utils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
public class ObjectRedisSerializer implements RedisSerializer<Object> {
/**
* 定义序列化和反序列化转化类
*/
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
/**
* 定义转换空字节数组
*/
private static final byte[] EMPTY_ARRAY = new byte[0];
@Override
public byte[] serialize(Object obj) throws SerializationException {
byte[] byteArray = null;
if (null == obj) {
System.err.println("----------------------------->:Redis待序列化的对象为空.");
byteArray = EMPTY_ARRAY;
} else {
try {
byteArray = serializer.convert(obj);
} catch (Exception e) {
System.err.println("----------------------------->Redis序列化对象失败,异常:"+e.getMessage());
byteArray = EMPTY_ARRAY;
}
}
return byteArray;
}
@Override
public Object deserialize(byte[] datas) throws SerializationException {
Object obj = null;
if((null == datas)|| (datas.length == 0)){
System.out.println("---------------------------------->Redis待反序列化的对象为空.");
}else{
try {
obj = deserializer.convert(datas);
} catch (Exception e) {
System.out.println("------------------------------------->Redis反序列化对象失败,异常:"+e.getMessage());
}
}
return obj;
}
}
package com.xx.zonghe.controller;
import com.alibaba.fastjson.JSON;
import com.shengquan.zonghe.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
/**
* @author 彭伟
* @date 2018/8/28 9:47
*/
@RestController
@RequestMapping("/redis")
public class RedisController {
private String testString = "testString";
private String userKey = "userKey";
//
// @Autowired
// private RedisTemplate<String, Object> redisTemplate;
@Autowired
private RedisTemplate<Serializable, Object> redisTemplate;
// @Autowired
// private StringRedisTemplate stringRedisTemplate;
@GetMapping("/add")
public String add() {
//1,添加一个Value为String
// stringRedisTemplate.opsForValue().set(testString, "测试存储字符串类型");
//2,添加一个Value为对象
User user = new User();
user.setId("1");
user.setName("张三");
user.setPassword("1111");
//redisTemplate.opsForValue().set(userKey, user);
// redisTemplate.opsForValue().set(userKey, user);
System.out.println("添加radis==="+JSON.toJSONString(user));
redisTemplate.opsForValue().set(userKey,user);
redisTemplate.opsForValue().set(testString,"测试存储字符串类型");
return "成功";
}
@GetMapping("/getUser")
public User findUserByKey() {
User user = (User) redisTemplate.opsForValue().get(userKey);
System.out.println("从radis中获取user==="+ JSON.toJSONString(user));
return user;
}
@GetMapping("/getString")
public String findString() {
String s = (String) redisTemplate.opsForValue().get(testString);
System.out.println("从radis中获取getString=="+ s);
return s;
}
@GetMapping("/delete")
public String deleteByKey(){
//1,删除string类型
redisTemplate.delete(testString);
//2,删除user对象
redisTemplate.delete(userKey);
return "删除成功";
}
}