配置文件内容
@Configuration
@ComponentScan(basePackages = {“com.xd.redis”,“com.xd.dao.*”})
public class RedisConfig {
/**
* 直接new 一个对象返回,即默认它的各项属性(端口,主机名,密码等等)为默认值,
* @return
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig());
jedisConnectionFactory.setUsePool(true);
return jedisConnectionFactory;
}
/**
* jedis连接池配置,直接new 一个对象返回,使用默认值,如有需要可以为其各个属性配置值
* @return
*/
@Bean
public JedisPoolConfig jedisPoolConfig(){
return new JedisPoolConfig();
}
@Bean
public RedisTemplate<Serializable, Serializable> redisTemplate(){
RedisTemplate<Serializable, Serializable> redisTemplate = new RedisTemplate<Serializable, Serializable>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
}
下面是对redis存取的代码,是参照的另一位博主的博客,下面有这位博主的的博客的链接:
@Repository
public class UserDao implements IUserDao {
@A**utowired
private RedisTemplate<Serializable, Serializable> redisTemplate;**
public void saveUser(final User user) {
redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
redisConnection.set(redisTemplate.getStringSerializer().serialize("user.id."+user.getId()),
redisTemplate.getStringSerializer().serialize((user.getUsername())));
return null;
}
}
);
}
public User getUser(final long id) {
return redisTemplate.execute(new RedisCallback<User>() {
public User doInRedis(RedisConnection redisConnection) throws DataAccessException {
byte[] key = redisTemplate.getStringSerializer().serialize("user.id."+id);
if(redisConnection.exists(key)){
byte[] value = redisConnection.get(key);
String username = redisTemplate.getStringSerializer().deserialize(value);
User user = new User();
user.setUsername(username);
user.setId(id);
return user;
}
return null;
}
});
}
}
详情请参考原文:https://blog.csdn.net/x763795151/article/details/53742309