netty學習(三)springboot+netty+mybatis

[TOC]java

前言

前面寫到了springboot整合netty,只是使用netty將數據處理了,尚未存入數據庫,如今就把mybatis加進去吧;恰好最近也有一位讀者問到了這個問題;mysql

正文

首先引入pom依賴git

<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>
        <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.29.Final</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- druid的starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
複製代碼

配置

配置文件配置:github

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/authority?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      initial-size: 2
      max-active: 30
      min-idle: 2
      max-wait: 1234
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 5
#mybatis
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity
複製代碼

記住springboot的啓動類上要掃描mapper接口包spring

springboot中啓動netty

其實springboot中啓動netty的方式有不少種,前一篇netty文章中我經過實現CommandLineRunner接口來啓動netty服務,後面寫了一篇springbean生命週期,發現springboot能夠用配置bean的方式啓動netty服務,在啓動方法上添加@PostConstruct註解,代碼以下:sql

NettyStart

@Component
public class NettyStart {
    @Resource
    private ServerHandler serverHandler;
    
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workGroup = new NioEventLoopGroup();
    
    /** * 啓動netty服務 * @throws InterruptedException */
    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap b=new ServerBootstrap();
        b.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(serverHandler);
                    }
                });
        ChannelFuture future = b.bind(8080).sync();
        if (future.isSuccess()) {
            System.out.println("啓動 Netty 成功");
        }
    }
    /** * 銷燬 */
    @PreDestroy
    public void destroy() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
        System.out.println("關閉 Netty 成功");
    }
}

複製代碼

其中的serverHandler是經過依賴注入的方式注入的,這是爲了後面serverHandler類中能夠直接依賴注入;數據庫

ServerHandler類:

@Component
@Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Resource
    private UserService userService;

    /** * 獲取數據 * @param ctx 上下文 * @param msg 獲取的數據 */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ByteBuf readMessage= (ByteBuf) msg;
        System.out.println(readMessage.toString(CharsetUtil.UTF_8));
        List<User> users = userService.selectAll();
        users.forEach(user-> System.out.println(user.toString()));
    }
}
複製代碼

這個類加了@Component@Sharable註解,前一個不用解釋了,後一個我的以爲:這個類被spring託管了,那麼這個類就是單例,至關於這個類是共享的,因此得加@Sharable註解,關於該註解,能夠參考這篇文章:blog.csdn.net/supper10090… 這裏我注入了UserService類,這裏是操做數據庫的方法springboot

UserService

public interface UserService {
    /** * 獲取全部數據 * @return */
    List<User> selectAll();
}
複製代碼

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }
}

複製代碼

實體類

public class User implements Serializable {
    private static final long serialVersionUID = -7776017450107481817L;
    private int id;
    private String name;
    private String password;
    private int age;
    private Date birthday;
}
複製代碼

set,get方法省略mybatis

mapper接口

@Repository
public interface UserMapper {
    List<User> selectAll();
}
複製代碼

mapper的xml文件就補貼上來了;併發

輸出結果

測試
User{id=1, name='admin', password='admin', age=10, birthday=Tue May 30 00:00:00 CST 2017}
User{id=2, name='teacher', password='teacher', age=30, birthday=null}
User{id=3, name='student', password='student', age=20, birthday=null}

複製代碼

個人mapper中只是查詢數據庫操做,並無寫如數據,若是要寫入,修改mapper就好了;

總結

在不少關於netty的項目或博客中都是經過new的方式添加pipeline的,而我這裏用了注入的方式;我是由於我所作的這個項目是單機版的,至關於就是全部的功能都在一個項目裏面,並且單個功能操做數據庫的頻率比較高,並且我作的這個項目處理不了高併發,併發高了就會gg;因此我所寫的這些文章都是從項目上所學來的; 若是經過new的方式添加pipeline,那麼在處理數據的方法中能夠經過一個類實現ApplicationContextAware接口來獲取spring上下文;而後在調用bean,操做數據庫;下面是參考連接: 在非spring管理的類中,使用spring管理的類

  • springboot啓動netty的方式有不少:一種是實現CommandLineRunner接口;一種是配置bean,指定初始化方法;還有其餘的

源碼在GitHub上面

參考文章:crossoverjie.top/2018/05/24/…

相關文章
相關標籤/搜索