Getting started with programming in Kafka.net (iv)

Source: Internet
Author: User
Tags unsub zookeeper

Create a new CMD window, zkserver command to start zookeeper
Open another CMD window and enter:

CD D:\Worksoftware\Apachekafka2.11\bin\windows

Kafka-server-start  D:\Worksoftware\Apachekafka2.11\ Config\server.properties
Delete theme: E:\worksoftware\kafka2.11\bin\windows>kafka-run-class.bat Kafka.admin.TopicCommand--delete--topic Testsiso--zookeeper localhost:2181

Kafka Delete topic hint marked for deletion
And not really deleted if you want to really delete

The Kafka_2.10/config/server.properties file in each machine joins the Delete.topic.enable=true

Finally, after all the machines have been restarted Kafka startup Kafka is successful, you can run the project

Quoting the Kafka-net.dll Program.cs

 Internal class Program {private static void Main (string[] args) {string header = ' Kafka

            Test ";
            Console.title = header;
            Console.WriteLine (header);

            Consolecolor color = Console.foregroundcolor;

            var pub = new Kafkahelper ("Test", true);

            var sub = new Kafkahelper ("Test", false); Task.run (() => {while (true) {string msg = string.
                    Format ("{0} This is a test message", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss.fff")); Pub.

                    Pub (New list<string> {msg});
                    Console.foregroundcolor = consolecolor.red;
                    Console.WriteLine ("Send message:" + msg);
                    Console.foregroundcolor = color;
                Thread.Sleep (2000);

            }
            }); Task.run (() => Sub. Sub (msg => {console.foregroundcolor = Consolecolor.Green;
                Console.WriteLine ("received message: {0}", msg);
            Console.foregroundcolor = color;

            }));
        Console.ReadLine (); }
    }
KafkaHelper.cs Code:
    <summary>///Kafka Auxiliary class///</summary> public sealed class Kafkahelper {Priv

        Ate readonly kafkaconfig _config;
        Private ReadOnly Consumerhelper _consumerhelper;
        Private readonly bool _isproducer = true;
        Private ReadOnly Producehelper _producehelper;

        Private Brokerhelper _brokerhelper; <summary>///Kafka Auxiliary class construction method///</summary>///<param name= "sectionname" > Config node name </param>///<param name= "Isproducer" ></param> public kafkahelper (String SE
            Ctionname, bool Isproducer = true) {_isproducer = Isproducer;
            _config = Kafkaconfig.getconfig (sectionname); _brokerhelper = new Brokerhelper (_config.
            Broker);
            if (isproducer) _producehelper = new Producehelper (_brokerhelper);
else _consumerhelper = new Consumerhelper (_brokerhelper);        ///<summary>///is producer mode///</summary> public bool Isproducer
        {get {return _isproducer;} ///<summary>///send messages to Queues///</summary>///<param name= "topic"
        ;</param>///<param name= "datas" ></param>///<param name= "ACKs" ></param> <param name= "Timeout" ></param> public void Pub (list<string> datas, short acks = 1, Ti Mespan?
        Timeout = default (TimeSpan?)) {_producehelper.pub (_config).
        Topic, datas, ACKs, timeout, messagecodec.codecnone); ///<summary>///Subscription message///</summary>///<param name= "Onmsg" >&lt ;/param> public void Sub (action<string> onmsg) {_consumerhelper.sub (_config.
        Topic, onmsg); ///<summary>///Unsubscribe///</summary> public void Unsub () {_consumerhelper.unsub (); }
    }
KafkaConfig.cs Code:
 <summary>///Kafka Configuration Class///</summary> public class Kafkaconfig:configurationsection { <summary>///Current configuration name///This attribute must be///</summary> public stri

        ng sectionname {get; set;} <summary>///agent///</summary> [ConfigurationProperty ("broker", isrequired =
            true)] public string Broker {get {return (string) base["Broker"];
        set {base["broker"] = value;} ///<summary>///Theme///</summary> [ConfigurationProperty ("topic", IsR
            Equired = True]] public string Topic {get {return (string) base[' Topic '];
        set {base["topic"] = value;} 
        #region Create the Kafka configuration class from the configuration file///<summary>///Get the default Kafka configuration class///</summary>
<returns></returns>        public static Kafkaconfig GetConfig () {return (Kafkaconfig) configurationmanager.getsection ("
        Kafkaconfig "); }///<summary>///Gets the specified Kafka configuration class///</summary>///<param name= "sect Ionname "></param>///<returns></returns> public static Kafkaconfig GetConfig (string
            sectionname) {var section = (kafkaconfig) configurationmanager.getsection (sectionname);
            As with the default configuration, you can omit the if (section = = null) section = GetConfig ();
            if (section = = null) throw new Configurationerrorsexception ("Kafkacofng node" + sectionname + "Not configured."); Section.
            SectionName = sectionname;
        return section; }///<summary>///read configuration from specified location///</summary>///<param name= "FileName "></param>///<param name=" sectionname "></param>///<returns></returns> public static Kafkaconfig GetConfig (string fileName, str ing sectionname) {return GetConfig (configurationmanager.openmappedmachineconfiguration) (New Configurat
        Ionfilemap (FileName)), sectionname); }///<summary>///read configuration from specified configuration///</summary>///<param na Me= "config" ></param>///<param name= "sectionname" ></param>///<returns></r eturns> public static kafkaconfig getconfig (Configuration Config, string sectionname) {if
            (config = = null) throw new Configurationerrorsexception ("Incoming configuration cannot be empty"); var section = (kafkaconfig) config.
            GetSection (sectionname);
            if (section = = null) throw new Configurationerrorsexception ("Kafkacofng node" + sectionname + "Not configured."); Section. sectionname = sectionName;
        return section; } #endregion}
BrokerHelper.cs Code:
<summary>
    ///proxy class
    ///</summary>
    internal class Brokerhelper
    {
        private ReadOnly string _broker;

        Public Brokerhelper (String broker)
        {
            _broker = broker;
        }

        <summary>
        ///     The routing object of the proxy
        ///</summary>
        ///<returns></returns> Public
        brokerrouter Getbroker ()
        {
            var options = new Kafkaoptions (new Uri (String). Format ("http://{0}", _broker));
            return new Brokerrouter (options);
        }
    
ConsumerHelper.cs Code:
///<summary>///Consumer Helper Class///</summary> internal class Consumerhelper

        {private readonly brokerhelper _brokerhelper;

        Private Consumer _consumer;

        private bool _unsub;
        Public Consumerhelper (Brokerhelper brokerhelper) {_brokerhelper = Brokerhelper;

            public void Sub (string topic, action<string> onmsg) {_unsub = false;

            var Opiton = new Consumeroptions (topic, _brokerhelper.getbroker ());

            _consumer = new Consumer (Opiton); Task.run (() => {while (!_unsub) {Ienumerable<messa Ge> msgs = _consumer.
                    Consume (); Parallel.ForEach (msgs, msg => onmsg Encoding.UTF8.GetString (msg.
                Value)));
        }
            });
        public void Unsub () {_unsub = true; }
    }
ProduceHelper.cs Code:
<summary>///producer Helper Class///</summary> internal class Producehelper:idisposable {p
        Rivate readonly Producer _producer;

        Private Brokerhelper _brokerhelper;

            Public Producehelper (Brokerhelper brokerhelper) {_brokerhelper = Brokerhelper;
        _producer = new producer (_brokerhelper.getbroker ()); public void Dispose () {if (_producer!= null) _producer.
        Dispose (); ///<summary>///send messages to Queues///</summary>///<param name= "topic" >&lt
        ;/param>///<param name= "datas" ></param>///<param name= "ACKs" ></param>  <param name= "Timeout" ></param>///<param name= "codec" ></param> public void Pub (String topic, list<string> datas, short acks = 1, TimeSpan? timeout = default (TimeSpan?), Messagecodec codec = MesSagecodec.codecnone) {//var msgs = new list<message> (); foreach (string item in Datas)//{//Msgs.
            ADD (New Message (item)); } var msgs = datas. Select (item => new Message (item)).

            ToList (); _producer.
        Sendmessageasync (topic, msgs, ACKs, timeout, codec); }
    }
app.config
<?xml version= "1.0" encoding= "Utf-8"?>

<configuration>
  <configSections>
    < Section name= "Test" type= "Xxxxx.sssss.KafkaConfig, xxxxx.sssss"/>
  </configSections>
  <test Broker= "127.0.0.1:9092" topic= "Testsiso"/> <startup> <supportedruntime version= "v4.0"
    . netframework,version=v4.5 "/>
  </startup>
</configuration>
run the results as shown in figure:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.