netty编程之整合es实现存储以及搜索功能

写在前面

源码

本文看下netty如何整合es实现存储以及搜索功能。因为诸如聊天类的系统,一般都是需要提供类似于搜索这类的功能的,所以就很有必要引入es了,所以呢,本文就来看下。

以下,es和sprintboot等版本和我的保持一致,至少大版本保持一致,不然可能会遇到一些诡异的问题。

1:基础环境准备

1.1:安装es

参考ElasticSearch之安装和简单配置

1.2:创建需要使用的索引

复制代码
PUT goodsorder
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1
  }
}

设置分区和分片都是1。这也是默认的配置,不过这里显式配置了,更加清晰咯!

2:编程

2.1:es操作相关类

  • 仓库类
java 复制代码
public interface UserRepository extends ElasticsearchRepository<User, String> {

    Page<User> findByName(String name, Pageable pageable);

}
  • 服务类
java 复制代码
@Service("userService")
public class UserServiceImpl implements UserService {

    private UserRepository dataRepository;

    @Autowired
    public void setDataRepository(UserRepository dataRepository) {
        this.dataRepository = dataRepository;
    }

    @Override
    public void save(User user) {
        dataRepository.save(user);
    }

    @Override
    public void deleteById(String id) {
        dataRepository.deleteById(id);
    }

    @Override
    public User queryUserById(String id) {
        Optional<User> optionalUser = dataRepository.findById(id);
        return optionalUser.get();
    }

    @Override
    public Iterable<User> queryAll() {
        return dataRepository.findAll();
    }

    @Override
    public Page<User> findByName(String name, PageRequest request) {
        return dataRepository.findByName(name, request);
    }

}
  • es索引映射类
java 复制代码
//@Document(indexName = "dahuyou"/*, type = "group_user"*/)
@Document(indexName = "goodsorder", shards = 1, replicas = 1)
public class User {

    @Id
    private String id;
    private String name;   //姓名
    private Integer age;   //年龄
    private String level;  //级别
    private Date entryDate;//时间
    private String mobile; //电话
    private String email;  //邮箱
    private String address;//地址

    ...
}

2.2:netty消息处理器

java 复制代码
@Service("myServerHandler")
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(MyServerHandler.class);

    @Autowired
    private UserService userService;
  
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收msg消息{与上一章节相比,此处已经不需要自己进行解码}
        logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端接收到消息:" + JSON.toJSONString(msg));
        //接收数据写入到Elasticsearch
        TransportProtocol transportProtocol = (TransportProtocol) msg;
        userService.save((User) transportProtocol.getObj());
    }

    ...
}

在消息处理器中会将收到的消息写入到es中。

2.3:netty客户端测试类

java 复制代码
public class ApiTest {

    public static void main(String[] args) {
        System.out.println("hi dahuyouaaaaa!!!!!!");
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    //对象传输处理
                    channel.pipeline().addLast(new ObjDecoder(TransportProtocol.class));
                    channel.pipeline().addLast(new ObjEncoder(TransportProtocol.class));
                    // 在管道中添加我们自己的接收数据实现方法
                    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                        }
                    });
                }
            });
            ChannelFuture f = b.connect("127.0.0.1", 7397).sync();
            System.out.println("netty client start done. {}");

            TransportProtocol tp1 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "李小明", 1, "T0-1", new Date(), "13566668888", "[email protected]", "北京"));
            TransportProtocol tp2 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "张大明", 2, "T0-2", new Date(), "13566660001", "[email protected]", "南京"));
            TransportProtocol tp3 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "李书鹏", 2, "T1-1", new Date(), "13566660002", "[email protected]", "榆树"));
            TransportProtocol tp4 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "韩小雪", 2, "T2-1", new Date(), "13566660002", "[email protected]", "榆树"));
            TransportProtocol tp5 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "董叔飞", 2, "T4-1", new Date(), "13566660002", "[email protected]", "河北"));
            TransportProtocol tp6 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "候明相", 2, "T5-1", new Date(), "13566660002", "[email protected]", "下花园"));
            TransportProtocol tp7 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "田明明", 2, "T3-1", new Date(), "13566660002", "[email protected]", "东平"));
            TransportProtocol tp8 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "王大伟", 2, "T4-1", new Date(), "13566660002", "[email protected]", "西湖"));
            TransportProtocol tp9 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "李雪明", 2, "T1-1", new Date(), "13566660002", "[email protected]", "南昌"));
            TransportProtocol tp10 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "朱小飞", 2, "T2-1", new Date(), "13566660002", "[email protected]", "吉林"));
            TransportProtocol tp11 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "牛大明", 2, "T1-1", new Date(), "13566660002", "[email protected]", "长春"));
            TransportProtocol tp12 = new TransportProtocol(1, new User(UUID.randomUUID().toString(), "关雪儿", 2, "T2-1", new Date(), "13566660002", "[email protected]", "深圳"));

            //向服务端发送信息
            f.channel().writeAndFlush(tp1);
            f.channel().writeAndFlush(tp2);
            f.channel().writeAndFlush(tp3);
            f.channel().writeAndFlush(tp4);
            f.channel().writeAndFlush(tp5);
            f.channel().writeAndFlush(tp6);
            f.channel().writeAndFlush(tp7);
            f.channel().writeAndFlush(tp8);
            f.channel().writeAndFlush(tp9);
            f.channel().writeAndFlush(tp10);
            f.channel().writeAndFlush(tp11);
            f.channel().writeAndFlush(tp12);

            f.channel().closeFuture().syncUninterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}

运行后查看数据:

酱!!!

写在后面

参考文章列表

ElasticSearch之数据分片和故障转移

ElasticSearch之数据分片和故障转移

相关推荐
欧先生^_^13 分钟前
Spark 的一些典型应用场景及具体示例
大数据·分布式·spark
你熬夜了吗?17 分钟前
spring中使用netty-socketio部署到服务器(SSL、nginx转发)
服务器·websocket·spring·netty·ssl
八股文领域大手子1 小时前
如何给GitHub项目提PR(踩坑记录
大数据·elasticsearch·github
爱吃龙利鱼1 小时前
elk中kibana一直处于可用和降级之间且es群集状态并没有问题的解决方法
大数据·elk·elasticsearch
腾讯云大数据1 小时前
腾讯云ES一站式RAG方案获信通院“开源大模型+软件创新应用”精选案例奖
大数据·elasticsearch·开源·云计算·腾讯云
苍煜1 小时前
Elasticsearch(ES)中的脚本(Script)
大数据·elasticsearch·搜索引擎
Hello kele2 小时前
解构与重构:“整体部分”视角下的软件开发思维范式
大数据·经验分享·程序员·重构·项目管理·人月神话·沟通困局
_Poseidon2 小时前
搜索引擎的高级语法
搜索引擎·信息收集·baidu
Elastic 中国社区官方博客2 小时前
使用 LangGraph 和 Elasticsearch 构建强大的 RAG 工作流
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
^cola^2 小时前
ES历史版本下载
elasticsearch