【问题标题】:Spring boot + redis春季启动+redis
【发布时间】:2018-01-24 03:13:30
【问题描述】:

我正在演示带有 Redis 集成的 Spring Boot 应用程序。

我参考了各种网站参考,但最后我更喜欢遵循这个:http://www.baeldung.com/spring-data-redis-tutorial

我的代码与上面链接中给出的代码几乎相同。唯一的变化是我在我的 RestController 类中自动装配了 StudentRepository。

现在,当我当时尝试执行 maven-install 时,它给了我一个错误

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'studentRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentRepositoryImpl' defined in file [/home/klevu/work/Nimesh/Spring Boot Workspace/bootDemo/target/classes/com/example/demo/redis/repository/StudentRepositoryImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.example.demo.redis.repository.StudentRepositoryImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: No visible constructors in class com.example.demo.redis.repository.StudentRepositoryImpl

当我试图让构造函数公开时,它会成功创建构建。但我不知道我应该在这里做还是不做。我在想,我应该能够进行设置器注入,而不是自动装配构造函数。我也在下面尝试过:

@Autowired
private RedisTemplate<String, Student> redisTemplate;

但它也不起作用。

package com.example.demo.redis.repository;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.example.demo.redis.bean.Student;

@Repository
public class StudentRepositoryImpl implements StudentRepository {

    private static final String KEY = "Student";

    //@Autowired
    private RedisTemplate<String, Student> redisTemplate;

    private HashOperations<String, String, Student> hashOps;

    @Autowired
    private StudentRepositoryImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    private void init() {
        hashOps = redisTemplate.opsForHash();
    }

    @Override
    public void saveStudent(Student person) {
        hashOps.put(KEY, person.getId(), person);
    }

    @Override
    public void updateStudent(Student person) {
        hashOps.put(KEY, person.getId(), person);
    }

    @Override
    public Student findStudent(String id) {
        return hashOps.get(KEY, id);
    }

    @Override
    public Map<String, Student> findAllStudents() {
        return hashOps.entries(KEY);
    }

    @Override
    public void deleteStudent(String id) {
        hashOps.delete(KEY, id);
    }
}

RedisConfiguration 是默认的,代码如下:

package com.example.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfiguration {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }


}

Spring boot 主入口点声明如下:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;

@SpringBootApplication
@EnableMongoRepositories(basePackages = {"com.example.demo.mongo.repository"} )
@EnableRedisRepositories(basePackages = {"com.example.demo.redis.repository"})
public class BootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class, args);
    }
}

测试redis的演示控制器如下:

package com.example.demo.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.redis.bean.Student;
import com.example.demo.redis.repository.StudentRepository;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping
    public ResponseEntity<Map<String, Student>> index() {
        Map<String, Student> students = studentRepository.findAllStudents();
        return new ResponseEntity<Map<String, Student>>(students, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable("id") String id) {
        Student student = studentRepository.findStudent(id);
        return new ResponseEntity<Student>(student, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Student> saveStudent(@RequestBody Student student) {
        studentRepository.saveStudent(student);
        return new ResponseEntity<Student>(student, HttpStatus.CREATED);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/{id}")
    public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
        studentRepository.updateStudent(student);
        return new ResponseEntity<Student>(student, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public ResponseEntity<Student> deleteMessage(@PathVariable("id") String id) {
        studentRepository.deleteStudent(id);
        return new ResponseEntity<Student>(HttpStatus.OK);
    }
}

【问题讨论】:

  • 也发布 studentRepository 代码。
  • 请放代码,因为我没有教程。
  • 可以将代码推送到 Github 吗?
  • 我已经添加了代码。 @diguage 我认为这段代码包含了所有内容。如果你还需要 git,请告诉我。
  • 错误字面意思是有0个公共构造函数。博客错了。

标签: spring-boot redis spring-data-redis


【解决方案1】:

你可以使用 Spring Data Redis

添加依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

启用缓存

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class RedisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisDemoApplication.class, args);
    }

}

在redis中缓存的方法处添加Cacheable注解

   @Cacheable(value = "employee", key = "#id")
    public Employee getEmployee(Integer id) {
        log.info("Get Employee By Id: {}", id);
        Optional<Employee> employeeOptional = employeeRepository.findById(id);
        if (!employeeOptional.isPresent()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id Not foud");
        }
        return employeeOptional.get();
    }

【讨论】:

    【解决方案2】:

    您将构造函数设置为私有...将其更改为公共

    @Autowired
    public StudentRepositoryImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    

    【讨论】:

      【解决方案3】:

      更改以下redis配置:

      您的原件:

      @Bean
      public RedisTemplate<String, Object> redisTemplate() {
         ...
      }
      

      改成:

      @Bean
      public RedisTemplate<String, ?> redisTemplate(){
          ...
      }
      

      它现在应该适合你了。

      【讨论】:

        猜你喜欢
        • 2017-09-11
        • 2015-04-18
        • 2017-06-24
        • 2015-08-22
        • 2015-09-18
        • 2015-03-20
        • 2016-08-22
        • 2016-07-22
        • 1970-01-01
        相关资源
        最近更新 更多