一起来学SpringBoot(九)NoSQL数据库

Nosql的全称是Not Only Sql,这个概念早起就有人提出,在09年的时候比较火。Nosql指的是非关系型数据库,而我们常用的都是关系型数据库。就像我们常用的mysql,sqlserver一样,这些数据库一般用来存储重要信息,应对普通的业务是没有问题的。但是,随着互联网的高速发展,传统的关系型数据库在应付超大规模,超大流量以及高并发的时候力不从心。而就在这个时候,Nosql得到的告诉的发展。
这里要说明我只用过两种nosql,今天就放上去springboot对他们的一些配置

Redis

先添加依赖

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

这里需要说明一下

首先呢看下yml的配置

spring:
    redis:
      host: 127.0.0.1
      port: 6379
      password:
      jedis:
        pool:
          max-active: 9
          max-idle: 8
          max-wait: -1ms
          min-idle: 0
      database: 0  # 指定存储的数据是哪个库

如果集群了咋办呢 添加如下配置 这里要修改

spring:
    redis:
        host: 192.168.8.132
        port: 6379
        timeout: 20000
        cluster:
            nodes: 192.168.8.134:7000,192.168.8.134:7001,192.168.8.134:7002
            maxRedirects: 6
        pool:
            max-active: 8
            min-idle: 0
            max-idle: 8
            max-wait: -1

springboot 使用的是RedisTemplate 来简化操作,这里建议提前配置一下主要是对序列化的处理

package com.maoxs.conf;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis缓存配置
 *
 * @author FuLin
 */
@Configuration
public class RedisConfig {
    // 以下两种redisTemplate自由根据场景选择
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

使用的时候用@Autowrid 注入即可 切记存入redis的类一定要实现Serializable 接口,不然在流的传输中会受到影响。这里就不演示怎么使用了以后我会出使用帖子 这里放个学习手册 RedisTemplate 学习手册


mongodb

依赖依赖依赖

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

然后呢yml

spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/test  #如果没有test就会自动创建

集群呢就这样写

spring:
  data:
    mongodb:
      uri: mongodb://192.168.8.101:27017,192.168.8.101:27018/test  #如果没有test就会自动创建

有密码了怎么办

spring:
  data:
    mongodb:
      uri: mongodb://user:[email protected]:27017/test  #如果没有test就会自动创建

springboot中是使用MongoTemplate 来简化操作的。写个简单的例子 创建一个实体类

package com.maoxs.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private  Long id;
    private String name;
    private String password;

    public User(Long id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("User{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", password='").append(password).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
package com.maoxs.dao;

import com.maoxs.pojo.User;

import java.util.List;

public interface UserDao {
    void add(User user) throws Exception;

    void update(User user) throws Exception;

    void delete(Long id) throws Exception;

     List<User> select(int page, int size)throws Exception;
}
package com.maoxs.dao.impl;

import com.maoxs.dao.UserDao;
import com.maoxs.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDaoImpl implements UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加
     * @param user
     * @throws Exception
     */
    @Override
    public void add(User user) throws Exception {
        mongoTemplate.save(user);
    }

    /**
     * 根据id更新
     * @param user
     * @throws Exception
     */
    @Override
    public void update(User user) throws Exception {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("name", user.getName()).set("password", user.getPassword());
        mongoTemplate.updateFirst(query, update, User.class);
    }

    /**
     * 删除
     * @param id
     * @throws Exception
     */
    @Override
    public void delete(Long id) throws Exception {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
    }

    /**
     * 分页
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @Override
    public  List<User>  select(int page,int size) throws Exception {
        Query query = new Query();
        query.skip(page*size).limit(size);
        List<User> users = mongoTemplate.find(query, User.class);
        return users;
    }
}

然后是测试类

package com.maoxs;

import com.maoxs.dao.UserDao;
import com.maoxs.pojo.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Random;
import java.util.UUID;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMongodbApplicationTests {
    @Autowired
    private UserDao userDao;

    @Test
    public void add() throws Exception {
        Random rand = new Random();
        for (int i = 1; i <= 50; i++) {
            User user = new User(rand.nextInt(100) + 1L, "jacl" + i, UUID.randomUUID().toString());
            userDao.add(user);
        }
    }

    @Test
    public void update() throws Exception {
        User user = new User(79L, "fulin", "wangle");
        this.userDao.update(user);
    }

    @Test
    public void del() throws Exception {
        this.userDao.delete(5L);
    }

    @Test
    public void selcet() throws Exception {
        List<User> select = this.userDao.select(1, 10);
        select.forEach(p -> {
            System.out.println(p.toString());
        });
    }
}

在用robo看看效果

在用robo看看效果

在这里插入图片描述

ok没问题 这里呢在放一个学习手册 MongoTemplate 学习手册

本博文是基于springboot2.x 如果有什么不对的请在下方留言。

相关连接:

个人博客地址 : www.fulinlin.com

csdn博客地址:https://blog.csdn.net/qq_32867467

集合源码地址 : https://gitee.com/Maoxs/springboot-test

注:如果不对联系本宝宝及时改正~~

猜你喜欢

转载自blog.csdn.net/qq_32867467/article/details/82944491