JAVA的Record类型的instanceof和自动判空机制------JAVA

package com.example.demo;

import org.junit.Test;

import java.util.ArrayList;

/**
 * Unit test for simple App.
 */
public class StudentTest {
    @Test
    public void Test01(){
//        创建Record对象
//        这里也会先执行紧凑的构造方法
        Student Rose = new Student(1001,"Rose","abc",15);
        System.out.println(Rose.toString());
        Integer age = Rose.age();
        System.out.println(age);
        String name = Rose.name();
        System.out.println(name);
        String email = Rose.email();
        System.out.println(email);
        System.out.println("哈哈");
        System.out.println(Rose.concat());
        System.out.println(Student.emailToUpperCase("Dasd"));
        Student jack = new Student(2001, "Jack");
        System.out.println(jack);
    }
    @Test
    public void Test02(){
        ProductRecord record = new ProductRecord(1,"手机",200);
        record.print();
        ArrayList<Object> objects = new ArrayList<>();
        System.out.println(objects.get(1));
    }
    @Test
    public void Test03(){
//        定义java的Record
        record SaleRecord(String saleId,String productName,Double money){}
        SaleRecord saleRecord = new SaleRecord("S001","显示器",3000.1);
        System.out.println(saleRecord);
    }

    @Test
    public void Test04() {
        Address address = new Address("北京","大兴区凉水河二街八号10栋3层","100176");
        PhoneNumber phoneNumber = new PhoneNumber("010","400-8080-105");
        Customer customer = new Customer("c101","Jack",phoneNumber,address);
        System.out.println(customer);
    }
    @Test
    public void Test05(){
        Person person = new Person("Jack",10);
        SomeService someService = new SomeService();
        boolean eligible = someService.isEligible(person);
        System.out.println(eligible);
    }
    @Test
    public void Test06(){
        SomeService someService = new SomeService();
        boolean eligible = someService.isEligible(null);
        System.out.println(eligible);
    }
}
package com.example.demo;

import org.junit.Test;

import java.util.ArrayList;

/**
 * Unit test for simple App.
 */
public class StudentTest {
    @Test
    public void Test01(){
//        创建Record对象
//        这里也会先执行紧凑的构造方法
        Student Rose = new Student(1001,"Rose","abc",15);
        System.out.println(Rose.toString());
        Integer age = Rose.age();
        System.out.println(age);
        String name = Rose.name();
        System.out.println(name);
        String email = Rose.email();
        System.out.println(email);
        System.out.println("哈哈");
        System.out.println(Rose.concat());
        System.out.println(Student.emailToUpperCase("Dasd"));
        Student jack = new Student(2001, "Jack");
        System.out.println(jack);
    }
    @Test
    public void Test02(){
        ProductRecord record = new ProductRecord(1,"手机",200);
        record.print();
        ArrayList<Object> objects = new ArrayList<>();
        System.out.println(objects.get(1));
    }
    @Test
    public void Test03(){
//        定义java的Record
        record SaleRecord(String saleId,String productName,Double money){}
        SaleRecord saleRecord = new SaleRecord("S001","显示器",3000.1);
        System.out.println(saleRecord);
    }

    @Test
    public void Test04() {
        Address address = new Address("北京","大兴区凉水河二街八号10栋3层","100176");
        PhoneNumber phoneNumber = new PhoneNumber("010","400-8080-105");
        Customer customer = new Customer("c101","Jack",phoneNumber,address);
        System.out.println(customer);
    }
    @Test
    public void Test05(){
        Person person = new Person("Jack",10);
        SomeService someService = new SomeService();
        boolean eligible = someService.isEligible(person);
        System.out.println(eligible);
    }
    @Test
    public void Test06(){
        SomeService someService = new SomeService();
        boolean eligible = someService.isEligible(null);
        System.out.println(eligible);
    }
}
package com.example.demo;

public class SomeService {
//    定义一个业务方法,判断成年
    public boolean isEligible(Object object){
//        record可以自动判断出这里是个null
        if( object instanceof Person(String name,Integer age)){
            return age >= 18;
        }
        return false;
    }
}
package com.example.demo;

public class SomeService {
//    定义一个业务方法,判断成年
    public boolean isEligible(Object object){
//        record可以自动判断出这里是个null
        if( object instanceof Person(String name,Integer age)){
            return age >= 18;
        }
        return false;
    }
}
package com.example.demo;

public record Person(String name,Integer age) {
}
package com.example.demo;

public record Person(String name,Integer age) {
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>demo</description>
	<properties>
		<java.version>21</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>21</source>
					<target>21</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>3.2.2</version>
       <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
       <java.version>21</java.version>
    </properties>
    <dependencies>
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <scope>test</scope>
       </dependency>
       <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <optional>true</optional>
       </dependency>
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
       </dependency>
    </dependencies>

    <build>
       <plugins>
          <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
             <configuration>
                <excludes>
                   <exclude>
                      <groupId>org.projectlombok</groupId>
                      <artifactId>lombok</artifactId>
                   </exclude>
                </excludes>
             </configuration>
          </plugin>
          <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <configuration>
                <source>21</source>
                <target>21</target>
             </configuration>
          </plugin>
       </plugins>
    </build>

</project>
  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是Java结合ZLMediaKit将RTSP流转换为WebSocket-FLV推送给前端浏览器进行播放的代码: ```java import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.util.ReferenceCountUtil; import org.zeromq.ZMQ; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Socket; import org.zeromq.ZMsg; import java.io.IOException; public class RtspToWebSocketHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(RtspToWebSocketHandler.class); private ZMQ.Context context; private ZMQ.Socket subscriber; private ZMQ.Socket publisher; private String publisherAddress; private String subscriberAddress; private String rtspUrl; private String roomId; private String sdp; private String tag; private boolean isPushStream; public RtspToWebSocketHandler(String publisherAddress, String subscriberAddress, String rtspUrl, String roomId, String sdp, String tag) { this.publisherAddress = publisherAddress; this.subscriberAddress = subscriberAddress; this.rtspUrl = rtspUrl; this.roomId = roomId; this.sdp = sdp; this.tag = tag; this.isPushStream = false; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } else { ReferenceCountUtil.release(msg); } } private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Handshake WebSocketServerProtocolHandler wsHandler = new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true, 65536); wsHandler.handshake(ctx.channel(), req); } private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { ctx.close(); return; } // Check for ping frame if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } // Check for binary frame if (!(frame instanceof BinaryWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } // Start pushing stream if (!isPushStream) { logger.info("Start pushing stream. roomId: {}", roomId); startPushStream(); isPushStream = true; } // Send WebSocket frame to ZLMediaKit BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame; byte[] data = binaryWebSocketFrame.content().nioBuffer().array(); publisher.sendMore(roomId).send(data); } private void startPushStream() { // Create ZMQ context and sockets context = ZMQ.context(1); subscriber = context.socket(ZMQ.SUB); publisher = context.socket(ZMQ.PUB); // Connect to subscriber and publisher subscriber.connect(subscriberAddress); subscriber.subscribe(tag.getBytes()); publisher.connect(publisherAddress); // Send stream info to ZLMediaKit JSONObject jsonObject = new JSONObject(); jsonObject.put("api", "addMediaSource"); jsonObject.put("url", rtspUrl); jsonObject.put("vhost", "default"); jsonObject.put("enable_rtsp", true); jsonObject.put("enable_rtp", true); jsonObject.put("enable_tcp", true); jsonObject.put("enable_udp", true); jsonObject.put("timeout_sec", 30); jsonObject.put("merge", true); jsonObject.put("hls_enabled", false); jsonObject.put("mp4_enabled", false); jsonObject.put("record_enabled", false); jsonObject.put("broadcast_enabled", true); jsonObject.put("room_id", roomId); jsonObject.put("sdp", sdp); publisher.sendMore(tag).send(jsonObject.toJSONString().getBytes()); logger.info("Send stream info to ZLMediaKit. roomId: {}, rtspUrl: {}", roomId, rtspUrl); // Start receiving stream from ZLMediaKit new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { try { ZMsg zMsg = ZMsg.recvMsg(subscriber); if (zMsg == null) { continue; } byte[] data = zMsg.getLast().getData(); BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(Unpooled.wrappedBuffer(data)); ctx.channel().writeAndFlush(binaryWebSocketFrame); logger.debug("Received stream from ZLMediaKit. roomId: {}, data length: {}", roomId, data.length); } catch (IOException e) { logger.error("Error receiving stream from ZLMediaKit. roomId: {}", roomId, e); break; } } // Close sockets subscriber.close(); publisher.close(); context.term(); }).start(); } private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } } ``` 使用方法: 1. 在Netty的ChannelPipeline中加入RtspToWebSocketHandler。 2. 当前端连接WebSocket时,会触发RtspToWebSocketHandler的channelRead方法,此时需要调用WebSocketServerProtocolHandler的handshake方法进行握手。 3. 当前端发送WebSocket帧时,会触发RtspToWebSocketHandler的channelRead方法,此时会将WebSocket帧发送给ZLMediaKit,ZLMediaKit会将转换后的FLV数据发送给RtspToWebSocketHandler,RtspToWebSocketHandler再将FLV数据发送给前端浏览器进行播放。 4. 当前端关闭WebSocket时,会触发RtspToWebSocketHandler的handleWebSocketFrame方法,此时需要关闭ZMQ的subscriber和publisher。 注意事项: 1. 代码中的ZLMediaKit的接口参数可能与实际情况不符,需要根据实际情况进行修改。 2. 代码中的ZMQ版本为4.x,如果使用的是3.x版本需要进行相应修改。 3. 代码中使用了Fastjson和Netty,需要进行相应依赖的引入。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧约Alatus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值