当前位置: 代码迷 >> 综合 >> springboot学习笔记|第三篇:Spring Boot+Nosql
  详细解决方案

springboot学习笔记|第三篇:Spring Boot+Nosql

热度:80   发布时间:2023-11-06 04:44:22.0

目录

    • 1.整合Redis
    • 2.整合MongoDB
    • 3.Session共享

1.整合Redis

  • docker安装Redis

(1)拉取镜像

$ docker pull redis

(2) 启动镜像

$ docker run -d -v /home/milk/docker/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf -p 6379:6379 --name redis f7302e4ab3a8 redis-server /usr/local/etc/redis/redis.conf --requirepass '123456'

requirepass:表示连接Redis密码
(3)进入Redis

$ docker exec -it redis redis-cli
  • Spring Boot整合Redis

(1) 引入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>

由于平时使用jedis比较多,在此排除默认的lettuce-core而使用jedis

(2) 配置application.yml

spring:redis:database: 0host: localhostport: 6379password: 123456jedis:pool:max-active: 8max-idle: 8min-idle: 0max-wait: -1ms
属性 说明
jedis.pool.max-active 连接池最大连接数
jedis.pool.max-idle 连接池最大空闲数
jedis.pool.min-idle 连接池最小空闲数
jedis.pool.min-idle 连接池最小空闲数
jedis.pool.max-wait 连接池最大阻塞等待时间,默然为-1
  • 创建实体
@Data
public class Book implements Serializable {
    /**id*/private int id;/**用户名*/private String name;/**作者*/private String author;
}
  • controller中使用
@RestController
public class BookController {
    @ResourceRedisTemplate redisTemplate;@ResourceStringRedisTemplate stringRedisTemplate;@GetMapping("/test1")public void test1(){
    ValueOperations<String, String> ops1 = stringRedisTemplate.opsForValue();ops1.set("name", "三国演义");String name = ops1.get("name");System.out.println(name);ValueOperations ops2 = redisTemplate.opsForValue();Book b1 = new Book();b1.setId(1);b1.setName("红楼梦");b1.setAuthor("曹雪芹");ops2.set("b1", b1);Book book = (Book) ops2.get("b1");System.out.println(book);}}

代码说明:
stringRedisTemplate:表示key和value值为字符串
redisTemplate:表示值可以为对象
opsForValue:获取操作对象,还有opsForZSet、opsForSet等方法

  • 测试:请求接口,获取相应 的值

2.整合MongoDB

  • docker安装MongoDB

(1)拉取镜像

$ docker pull mongo

(2)启动镜像

$ docker run -d -p 27017:27017 --name mongo -v /my/milk/docker/datadir:/data/db  mongo

(3) 创建用户

# 使用数据库`study`
use study
# 创建用户
db.createUser({
    user:'study',pwd:'123',roles:[{
    role:'readWrite',db:'study'}]})
# 检查用户,返回`1`则表示认证成功
db.auth('study','123')
  • Spring Boot整合mongodb

(1) 引入依赖

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

(2)配置application.yml

spring:data:mongodb:uri: mongodb://study:123@localhost:27017/study

(3)使用上例中实体
(4)使用MongoRepository存取(适合jpa查询方式)

public interface BookDao extends MongoRepository<Book,Integer> {
    List<Book> findByAuthorContains(String author);Book findByNameEquals(String name);
}

(5)Controller中使用

@RestController
public class BookController {
    @Resourceprivate BookDao bookDao;@GetMapping("/test2")public void test2(){
    List<Book> books = new ArrayList<>();Book b1 = new Book();b1.setId(1);b1.setName("天龙八部");b1.setAuthor("金庸");books.add(b1);Book b2 = new Book();b2.setId(2);b2.setName("射雕英雄传");b2.setAuthor("金庸");books.add(b2);bookDao.insert(books);List<Book> books1 = bookDao.findByAuthorContains("金庸");System.out.println(books1);Book book = bookDao.findByNameEquals("天龙八部");System.out.println(book);}
}

(6)使用MongoTemplate存取

@RestController
public class BookController {
    @Resourceprivate MongoTemplate mongoTemplate;@GetMapping("/test3")public void test3() {
    List<Book> books = new ArrayList<>();Book b1 = new Book();b1.setId(3);b1.setName("鹿鼎记");b1.setAuthor("金庸");books.add(b1);Book b2 = new Book();b2.setId(4);b2.setName("倚天屠龙记");b2.setAuthor("金庸");books.add(b2);mongoTemplate.insertAll(books);List<Book> all = mongoTemplate.findAll(Book.class);System.out.println(all);Book book = mongoTemplate.findById(3, Book.class);System.out.println(book);}
}

3.Session共享

在多个下游服务器时,为了保证多个服务器获得的session均一致,则在此将session存入Redis中,所有服务器获取的session均从Redis中获取

  • 引入依赖
<dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId>
</dependency>
  • 配置application.yml和上边配置Redis相同
  • 启动类增加注解@EnableRedisHttpSession
  • controller应用
@RestController
public class HelloController {
    @Value("${server.port}")public String port;@GetMapping("/save")public String saveName(@RequestParam("name") String name, HttpServletRequest request){
    request.getSession().setAttribute("name", name);return port;}@GetMapping("/get")public String getName(HttpServletRequest request){
    System.out.println(port);return port+":"+request.getSession().getAttribute("name").toString();}
}
  • 启动两个服务,端口分别为8888和9999,使用8888调用save方法,9999调用get方法获取到存入的session,表示session共享成功
  相关解决方案