Spring redisの操作

17429 ワード

Spring redisの操作
Spring redisの基本操作には、stringオブジェクト、hashオブジェクト、listオブジェクト、key削除、レコードの追加が含まれます.
import java.util.UUID;

    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.BoundHashOperations;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.stereotype.Repository;

    import com.hainan.cs.bean.User;
    @Repository(value="userDao")
    public class UserDaoImp extends RedisGeneratorDao{
        //  Hash hsetNX
        public boolean add(final User user){
            System.out.println(redisTemplate);
            boolean result=redisTemplate.execute(new RedisCallback(){
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    RedisSerializer serializer=getRedisSerializer();
                    byte[] key=serializer.serialize(user.getId());
                    byte[] name=serializer.serialize(user.getUsername());
                    byte[] password=serializer.serialize(user.getPassword());
                    Boolean r=connection.hSetNX(key, name,password);//hash     
                    return r;
                }
            });
            return result;
        }
        //  Hash hSet
        public boolean add1(final User user){
            System.out.println(redisTemplate);
            boolean result=redisTemplate.execute(new RedisCallback(){
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    RedisSerializer serializer=getRedisSerializer();
                    byte[] key=serializer.serialize(user.getId());
                    byte[] name=serializer.serialize(user.getUsername());
                    byte[] password=serializer.serialize(user.getPassword());
                    Boolean r=connection.hSet(key, name, password);// hSetNX  
                    return r;
                }
            });
            return result;
        }
        //  String
        public boolean add2(final User user){
            System.out.println(redisTemplate);
            boolean result=redisTemplate.execute(new RedisCallback(){
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    RedisSerializer serializer=getRedisSerializer();
                    byte[] key=serializer.serialize(user.getId());
                    byte[] name=serializer.serialize(user.getUsername());
                    Boolean r=connection.setNX(key, name);//  String  
                    return r;
                }
            });
            return result;
        }
        //  List
        public void add3(final String key,final String value){
            redisTemplate.execute(new RedisCallback(){
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    RedisSerializer serializer=getRedisSerializer();
                    byte[] a=serializer.serialize(key);
                    byte[] b=serializer.serialize(value);
                    connection.lPush(a, b);
                    return true;
                }
                });
        }
        //    
        public void deleteKey(String key){
            redisTemplate.delete(key);
        }
        //  hash      
        public void deleteRecord(String key,String id){
            BoundHashOperations bhops=redisTemplate.boundHashOps(key);
            bhops.delete(id);
        }
        //  
        public static void main(String args[]){
            ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring/application-config.xml");
            UserDaoImp udi=context.getBean(UserDaoImp.class);
            User u=new User();
            String id=UUID.randomUUID().toString();//      id
            u.setId("test1");
            u.setUsername(id);
            u.setPassword("123456");
            udi.add1(u);
            udi.deleteKey("1");
            udi.deleteRecord("test1", "zhangsan");
            udi.add3("listtest", "test");
        }
    }

2.springバージョンを4以上に変更してエラーを報告
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.data.redis.core.RedisTemplate com.hainan.cs.dao.RedisGeneratorDao.redisTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.redis.core.RedisTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
        at com.hainan.cs.dao.UserDaoImp.main(UserDaoImp.java:83)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.data.redis.core.RedisTemplate com.hainan.cs.dao.RedisGeneratorDao.redisTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.redis.core.RedisTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
        ... 13 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.redis.core.RedisTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)

xml方式で注入されたredisTemplateに問題があるため@Autowired関連に問題があることを説明する理由を見てみましょう.
`No qualifying bean of type [org.springframework.data.redis.core.RedisTemplate] found for dependency`

つまりここに問題があるのです
 id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
       

主に以下のプラグインによるもので、バージョンが4.0になるとエラーになります
<dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-contextartifactId>  
            <version>3.2.3.RELEASEversion>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-context-supportartifactId>  
            <version>3.2.3.RELEASEversion>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-beansartifactId>  
            <version>3.2.3.RELEASEversion>  
        dependency>