我正在尝试通过Java连接到Redis,我具有以下配置,
@SpringBootApplication
@Configuration
@ComponentScan(basePackages = "com.infy.redisDemo")
public class RedisDemoApplication {
@Bean
public LettuceConnectionFactory getConnectionFactory(){
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory("localhost",6379);
return lettuceConnectionFactory;
}
@Bean
public RedisTemplate<String,Object> getRedisTemplate(){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(getConnectionFactory());
return redisTemplate;
}
public static void main(String[] args) {
SpringApplication.run(RedisDemoApplication.class, args);
}
}
我的回购类:
@Repository
public class UserRepoImpl implements UserRepository {
private RedisTemplate<String, Object> redisTemplate;
private HashOperations hashOperations;
public final String key = "USER";
public UserRepoImpl(RedisTemplate redisTemplate,
HashOperations hashOperations) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
}
@Override
public void save(User user) {
hashOperations.put(key,user.getId(),user);
}
@Override
public void update(User user) {
hashOperations.put(key,user.getId(),user);
}
@Override
public Map findAll() {
return hashOperations.entries(key);
}
}
public interface UserRepository {
void save(User user);
void update(User user);
Map findAll();
}
我的控制器类如下,
@RestController
@RequestMapping("/rest/user")
public class RedisController {
private UserRepository userRepository;
public RedisController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/add/{id}/{name}")
public User add(@PathVariable String id,@PathVariable String name){
userRepository.save(new User(name,id,25000));
return userRepository.findById(id);
}
}
我在运行应用程序时遇到以下错误,
org.springframework.beans.factory.UnsatisfiedDependencyException:创建文件[redisDemo \ RedisController.class]中定义的名称为'redisController'的bean时出错:通过构造函数参数0表示的不满意依赖关系;嵌套的异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建文件[redisDemo \ repository \ UserRepoImpl.class]中定义的名称为'userRepoImpl'的bean时出错:通过构造函数参数1表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为“ org.springframework.data.redis.core.HashOperations”的合格Bean:预计至少有1个有资格作为自动装配候选的Bean。依赖项注释:{}
程序有什么问题?有什么建议可以使其正常工作吗?我需要使用jedisconnectionFactory吗?我正在使用Intellij,并且在Windows上 redis的版本是3.2 ,而 spring的版本是2.1.6 。
答案 0 :(得分:1)
您不需要在HashOperations hashOperations
构造函数中将UserRepoImpl
作为参数传递。相反,您可以从构造函数中删除此参数。
public UserRepoImpl(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
}