SpringBoot关联NOSql数据库 Redis

一,SpringBoot关联NOSql数据库 Redis
Redis数据库安装 :
Redis数据库安装最好是在Linux的环境下,因为Redis数据库本身开发的软件只有Linux版本,windows环境下的redis是后期windows开发的,并不是十分的稳定。

安装十分简单 :
    下载redis的安装包,将redis的存放路径在path环境变量中进行配置,以防在doc窗口中显示非命令错误。
    运行  redis-server.exe  redis.conf  就可以启动redis   (这个窗口不要关)  , 打开新的cmd窗口 , 到reids的存放路径下操作, 输入redis-cli.exe -h localhost
    没有错误的话就差不多正确了,可以通过set和get命令读写看看是否正确地进行了操作!
SpringBoot操作Redis数据库的简单实例 : 
                <name>redis</name>
                <description>Demo project for Spring Boot</description>
                <parent>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-parent</artifactId>
                    <version>1.5.9.RELEASE</version>
                    <relativePath/> <!-- lookup parent from repository -->
                </parent>
                <properties>
                    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
                    <java.version>1.8</java.version>
                </properties>

                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter</artifactId>
                    </dependency>

                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                    </dependency>
                    <!-- 添加redis的依赖jar包 -->
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-redis</artifactId>
                        <version>1.4.7.RELEASE</version>
                    </dependency>
                </dependencies>

                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                    </plugins>
                </build>
            </project>

我在导入jar包的时候一直出现这个jar包unknow的情况,修改下镜像为阿里云或者别的,或者你可以尝试修改redis jar包的版本号试试!,一般不会出错。

在application.properties文件中添加如下的配置:

        # REDIS (RedisProperties)
        # Redis数据库索引(默认为0)
        spring.redis.database=0
        # Redis服务器地址
        spring.redis.host=localhost
        # Redis服务器连接端口
        spring.redis.port=6379
        # Redis服务器连接密码(默认为空)
        spring.redis.password=
        # 连接池最大连接数(使用负值表示没有限制)
        spring.redis.pool.max-active=8
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        spring.redis.pool.max-wait=-1
        # 连接池中的最大空闲连接
        spring.redis.pool.max-idle=8
        # 连接池中的最小空闲连接
        spring.redis.pool.min-idle=0
        # 连接超时时间(毫秒)
        spring.redis.timeout=0

test文件中进行测试:

        @RunWith(SpringRunner.class)
        @SpringBootTest
        public class RedisApplicationTests {
            @Autowired
            private StringRedisTemplate stringRedisTemplate;
            @Test
            public void contextLoads() {
                //保存字符串
                stringRedisTemplate.opsForValue().set("key1","111");
                //Assert.assertEquals("111",stringRedisTemplate.opsForValue().get("key1"));
                System.out.print(stringRedisTemplate.opsForValue().get("key1"));
            }
        }

StringRedisTemplate对象能够对Redis进行读取操作,操作的类型为String,其实是相当于RedisTemplate<String,String>
RedisTemplate对象也能够对Redis进行操作,操作对象,相当于RedisTemplate<String,Object>

特别需要注意的是: SpringBoot并不支持直接使用对象,这就需要我们自己实现  RedisSerializer<T> 接口来对传入进来的对象
进行序列化和反序列化操作。

第一步:  创建实体类对象  (省略)
第二步:  实现对象的序列化接口
            public class RedisObjectSerializer implements RedisSerializer<Object> {

                private Converter<Object, byte[]> serializer = new SerializingConverter();
                private Converter<byte[], Object> deserializer = new DeserializingConverter();

                static final byte[] EMPTY_ARRAY = new byte[0];

                public Object deserialize(byte[] bytes) {
                    if (isEmpty(bytes)) {
                        return null;
                    }

                    try {
                        return deserializer.convert(bytes);
                    } catch (Exception ex) {
                        throw new SerializationException("Cannot deserialize", ex);
                    }
                }

                public byte[] serialize(Object object) {
                    if (object == null) {
                        return EMPTY_ARRAY;
                    }

                    try {
                        return serializer.convert(object);
                    } catch (Exception ex) {
                        return EMPTY_ARRAY;
                    }
                }

                private boolean isEmpty(byte[] data) {
                    return (data == null || data.length == 0);
                }
            }

第三步: 配置针对实体类的RedisTemplate实例

            @Configuration
            public class RedisConfig {

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

                @Bean
                public RedisTemplate<String, User> redisTemplate( RedisConnectionFactory factory){
                    RedisTemplate<String, User> template = new RedisTemplate<>();
                    template.setConnectionFactory(jedisConnectionFactory());
                    template.setKeySerializer(new StringRedisSerializer());
                    template.setValueSerializer(new RedisObjectSerializer());
                    return template;
                }
            }

第四步:编写测试类


            @RunWith(SpringJUnit4ClassRunner.class)
            @SpringBootTest
            public class RedisApplicationTests {

                @Autowired
                private RedisTemplate<String , User> redisTemplate;

                @Test
                public void test(){
                    //保存对象
                    User user = new User("liang",22,"男");
                    redisTemplate.opsForValue().set(user.getName(),user);

                    user = new User("yunqing", 25,"男");
                    redisTemplate.opsForValue().set(user.getName(),user);

                    Assert.assertEquals(20,redisTemplate.opsForValue().get("liang").getName());
                }

            }

这里写图片描述

猜你喜欢

转载自blog.csdn.net/WJHelloWorld/article/details/78794650