Search in sources :

Example 1 with Service

use of org.redkale.service.Service in project redkale by redkale.

the class Application method init.

public void init() throws Exception {
    System.setProperty("redkale.net.transport.poolmaxconns", "100");
    System.setProperty("redkale.net.transport.pinginterval", "30");
    System.setProperty("redkale.net.transport.checkinterval", "30");
    System.setProperty("redkale.convert.tiny", "true");
    System.setProperty("redkale.convert.pool.size", "128");
    System.setProperty("redkale.convert.writer.buffer.defsize", "4096");
    final String confDir = this.confPath.toString();
    final String homepath = this.home.getCanonicalPath();
    if ("file".equals(this.confPath.getScheme())) {
        File persist = new File(new File(confPath), "persistence.xml");
        if (persist.isFile())
            System.setProperty(DataSources.DATASOURCE_CONFPATH, persist.getCanonicalPath());
    } else {
        System.setProperty(DataSources.DATASOURCE_CONFPATH, confDir + (confDir.endsWith("/") ? "" : "/") + "persistence.xml");
    }
    // String pidstr = "";
    // try { //JDK 9+
    // Class phclass = Thread.currentThread().getContextClassLoader().loadClass("java.lang.ProcessHandle");
    // Object phobj = phclass.getMethod("current").invoke(null);
    // Object pid = phclass.getMethod("pid").invoke(phobj);
    // pidstr = "APP_PID  = " + pid + "\r\n";
    // } catch (Throwable t) {
    // }
    logger.log(Level.INFO, "APP_OSNAME = " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + "\r\n" + "APP_JAVA   = " + System.getProperty("java.runtime.name", System.getProperty("org.graalvm.nativeimage.kind") != null ? "Nativeimage" : "") + " " + System.getProperty("java.runtime.version", System.getProperty("java.vendor.version", System.getProperty("java.vm.version"))) + // graalvm.nativeimage 模式下无 java.runtime.xxx 属性
    "\r\n" + "APP_PID    = " + ProcessHandle.current().pid() + "\r\n" + RESNAME_APP_NODEID + " = " + this.nodeid + "\r\n" + "APP_LOADER = " + this.classLoader.getClass().getSimpleName() + "\r\n" + RESNAME_APP_ADDR + "   = " + this.localAddress.getHostString() + ":" + this.localAddress.getPort() + "\r\n" + RESNAME_APP_HOME + "   = " + homepath + "\r\n" + RESNAME_APP_CONF + "   = " + confDir.substring(confDir.indexOf('!') + 1));
    if (!compileMode && !(classLoader instanceof RedkaleClassLoader.RedkaleCacheClassLoader)) {
        String lib = config.getValue("lib", "${APP_HOME}/libs/*").trim().replace("${APP_HOME}", homepath);
        lib = lib.isEmpty() ? confDir : (lib + ";" + confDir);
        Server.loadLib(classLoader, logger, lib);
    }
    // ------------------------------------------------------------------------
    final AnyValue resources = config.getAnyValue("resources");
    if (resources != null) {
        resourceFactory.register(RESNAME_APP_GRES, AnyValue.class, resources);
        final AnyValue properties = resources.getAnyValue("properties");
        if (properties != null) {
            String dfloads = properties.getValue("load");
            if (dfloads != null) {
                for (String dfload : dfloads.split(";")) {
                    if (dfload.trim().isEmpty())
                        continue;
                    final URI df = RedkaleClassLoader.getConfResourceAsURI(configFromCache ? null : confDir, dfload.trim());
                    if (df != null && (!"file".equals(df.getScheme()) || df.toString().contains("!") || new File(df).isFile())) {
                        Properties ps = new Properties();
                        try {
                            InputStream in = df.toURL().openStream();
                            ps.load(in);
                            in.close();
                            ps.forEach((x, y) -> resourceFactory.register("property." + x, y.toString().replace("${APP_HOME}", homepath)));
                        } catch (Exception e) {
                            logger.log(Level.WARNING, "load properties(" + dfload + ") error", e);
                        }
                    }
                }
            }
            for (AnyValue prop : properties.getAnyValues("property")) {
                String name = prop.getValue("name");
                String value = prop.getValue("value");
                if (name == null || value == null)
                    continue;
                value = value.replace("${APP_HOME}", homepath);
                if (name.startsWith("system.property.")) {
                    System.setProperty(name.substring("system.property.".length()), value);
                } else if (name.startsWith("mimetype.property.")) {
                    MimeType.add(name.substring("mimetype.property.".length()), value);
                } else if (name.startsWith("property.")) {
                    resourceFactory.register(name, value);
                } else {
                    resourceFactory.register("property." + name, value);
                }
            }
        }
    }
    this.resourceFactory.register(BsonFactory.root());
    this.resourceFactory.register(JsonFactory.root());
    this.resourceFactory.register(BsonFactory.root().getConvert());
    this.resourceFactory.register(JsonFactory.root().getConvert());
    this.resourceFactory.register("bsonconvert", Convert.class, BsonFactory.root().getConvert());
    this.resourceFactory.register("jsonconvert", Convert.class, JsonFactory.root().getConvert());
    // 只有WatchService才能加载Application、WatchFactory
    final Application application = this;
    this.resourceFactory.register(new ResourceFactory.ResourceLoader() {

        @Override
        public void load(ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) {
            try {
                Resource res = field.getAnnotation(Resource.class);
                if (res == null)
                    return;
                // 远程模式不得注入
                if (src instanceof Service && Sncp.isRemote((Service) src))
                    return;
                Class type = field.getType();
                if (type == Application.class) {
                    field.set(src, application);
                } else if (type == ResourceFactory.class) {
                    boolean serv = RESNAME_SERVER_RESFACTORY.equals(res.name()) || res.name().equalsIgnoreCase("server");
                    field.set(src, serv ? rf : (res.name().isEmpty() ? application.resourceFactory : null));
                } else if (type == TransportFactory.class) {
                    field.set(src, application.sncpTransportFactory);
                } else if (type == NodeSncpServer.class) {
                    NodeServer server = null;
                    for (NodeServer ns : application.getNodeServers()) {
                        if (ns.getClass() != NodeSncpServer.class)
                            continue;
                        if (res.name().equals(ns.server.getName())) {
                            server = ns;
                            break;
                        }
                    }
                    field.set(src, server);
                } else if (type == NodeHttpServer.class) {
                    NodeServer server = null;
                    for (NodeServer ns : application.getNodeServers()) {
                        if (ns.getClass() != NodeHttpServer.class)
                            continue;
                        if (res.name().equals(ns.server.getName())) {
                            server = ns;
                            break;
                        }
                    }
                    field.set(src, server);
                } else if (type == NodeWatchServer.class) {
                    NodeServer server = null;
                    for (NodeServer ns : application.getNodeServers()) {
                        if (ns.getClass() != NodeWatchServer.class)
                            continue;
                        if (res.name().equals(ns.server.getName())) {
                            server = ns;
                            break;
                        }
                    }
                    field.set(src, server);
                }
            // if (type == WatchFactory.class) {
            // field.set(src, application.watchFactory);
            // }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Resource inject error", e);
            }
        }

        @Override
        public boolean autoNone() {
            return false;
        }
    }, Application.class, ResourceFactory.class, TransportFactory.class, NodeSncpServer.class, NodeHttpServer.class, NodeWatchServer.class);
    // ------------------------------------- 注册 java.net.http.HttpClient --------------------------------------------------------
    resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
        try {
            if (field.getAnnotation(Resource.class) == null)
                return;
            java.net.http.HttpClient.Builder builder = java.net.http.HttpClient.newBuilder();
            if (resourceName.endsWith(".1.1")) {
                builder.version(HttpClient.Version.HTTP_1_1);
            } else if (resourceName.endsWith(".2")) {
                builder.version(HttpClient.Version.HTTP_2);
            }
            java.net.http.HttpClient httpClient = builder.build();
            field.set(src, httpClient);
            // 给其可能包含@Resource的字段赋值;
            rf.inject(httpClient, null);
            rf.register(resourceName, java.net.http.HttpClient.class, httpClient);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] java.net.http.HttpClient inject error", e);
        }
    }, java.net.http.HttpClient.class);
    // ------------------------------------- 注册 HttpSimpleClient --------------------------------------------------------
    resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
        try {
            if (field.getAnnotation(Resource.class) == null)
                return;
            HttpSimpleClient httpClient = HttpSimpleClient.create(asyncGroup);
            field.set(src, httpClient);
            // 给其可能包含@Resource的字段赋值;
            rf.inject(httpClient, null);
            rf.register(resourceName, HttpSimpleClient.class, httpClient);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] HttpClient inject error", e);
        }
    }, HttpSimpleClient.class);
    // --------------------------------------------------------------------------
    if (this.asyncGroup != null) {
        ((AsyncIOGroup) this.asyncGroup).start();
    }
    if (this.clusterAgent != null) {
        if (logger.isLoggable(Level.FINER))
            logger.log(Level.FINER, "ClusterAgent initing");
        long s = System.currentTimeMillis();
        if (this.clusterAgent instanceof CacheClusterAgent) {
            // 必须在inject前调用,需要赋值Resourcable.name
            String sourceName = ((CacheClusterAgent) clusterAgent).getSourceName();
            loadCacheSource(sourceName);
        }
        clusterAgent.setTransportFactory(this.sncpTransportFactory);
        this.resourceFactory.inject(clusterAgent);
        clusterAgent.init(clusterAgent.getConfig());
        this.resourceFactory.register(ClusterAgent.class, clusterAgent);
        logger.info("ClusterAgent init in " + (System.currentTimeMillis() - s) + " ms");
    }
    if (this.messageAgents != null) {
        if (logger.isLoggable(Level.FINER))
            logger.log(Level.FINER, "MessageAgent initing");
        long s = System.currentTimeMillis();
        for (MessageAgent agent : this.messageAgents) {
            this.resourceFactory.inject(agent);
            agent.init(agent.getConfig());
            this.resourceFactory.register(agent.getName(), MessageAgent.class, agent);
            this.resourceFactory.register(agent.getName(), HttpMessageClient.class, agent.getHttpMessageClient());
        // this.resourceFactory.register(agent.getName(), SncpMessageClient.class, agent.getSncpMessageClient()); //不需要给开发者使用
        }
        logger.info("MessageAgent init in " + (System.currentTimeMillis() - s) + " ms");
    }
    // ------------------------------------- 注册 HttpMessageClient --------------------------------------------------------
    resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
        try {
            if (field.getAnnotation(Resource.class) == null)
                return;
            if (clusterAgent == null) {
                HttpMessageClient messageClient = new HttpMessageLocalClient(application, resourceName);
                field.set(src, messageClient);
                // 给其可能包含@Resource的字段赋值;
                rf.inject(messageClient, null);
                rf.register(resourceName, HttpMessageClient.class, messageClient);
                return;
            }
            HttpMessageClient messageClient = new HttpMessageClusterClient(application, resourceName, clusterAgent);
            field.set(src, messageClient);
            // 给其可能包含@Resource的字段赋值;
            rf.inject(messageClient, null);
            rf.register(resourceName, HttpMessageClient.class, messageClient);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] HttpMessageClient inject error", e);
        }
    }, HttpMessageClient.class);
    initResources();
}
Also used : HttpClient(java.net.http.HttpClient) java.net(java.net) org.redkale.net(org.redkale.net) Service(org.redkale.service.Service) RedkaleClassLoader(org.redkale.util.RedkaleClassLoader) HttpClient(java.net.http.HttpClient) DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue) org.redkale.net.http(org.redkale.net.http)

Example 2 with Service

use of org.redkale.service.Service in project redkale by redkale.

the class Application method loadCacheSource.

private void loadCacheSource(final String sourceName) {
    final AnyValue resources = config.getAnyValue("resources");
    for (AnyValue sourceConf : resources.getAnyValues("source")) {
        if (!sourceName.equals(sourceConf.getValue("name")))
            continue;
        String classval = sourceConf.getValue("value");
        try {
            Class sourceType = CacheMemorySource.class;
            if (classval == null || classval.isEmpty()) {
                RedkaleClassLoader.putServiceLoader(CacheSourceProvider.class);
                List<CacheSourceProvider> providers = new ArrayList<>();
                Iterator<CacheSourceProvider> it = ServiceLoader.load(CacheSourceProvider.class, serverClassLoader).iterator();
                while (it.hasNext()) {
                    CacheSourceProvider s = it.next();
                    if (s != null)
                        RedkaleClassLoader.putReflectionPublicConstructors(s.getClass(), s.getClass().getName());
                    if (s != null && s.acceptsConf(sourceConf)) {
                        providers.add(s);
                    }
                }
                Collections.sort(providers, (a, b) -> {
                    Priority p1 = a == null ? null : a.getClass().getAnnotation(Priority.class);
                    Priority p2 = b == null ? null : b.getClass().getAnnotation(Priority.class);
                    return (p2 == null ? 0 : p2.value()) - (p1 == null ? 0 : p1.value());
                });
                for (CacheSourceProvider provider : providers) {
                    sourceType = provider.sourceClass();
                    if (sourceType != null)
                        break;
                }
            } else {
                sourceType = serverClassLoader.loadClass(classval);
            }
            RedkaleClassLoader.putReflectionPublicConstructors(sourceType, sourceType.getName());
            CacheSource source = sourceType == CacheMemorySource.class ? new CacheMemorySource(sourceName) : Modifier.isFinal(sourceType.getModifiers()) ? (CacheSource) sourceType.getConstructor().newInstance() : (CacheSource) Sncp.createLocalService(serverClassLoader, sourceName, sourceType, null, resourceFactory, sncpTransportFactory, null, null, sourceConf);
            cacheSources.add((CacheSource) source);
            resourceFactory.register(sourceName, CacheSource.class, source);
            resourceFactory.inject(source);
            if (!compileMode && source instanceof Service)
                ((Service) source).init(sourceConf);
            logger.info("[" + Thread.currentThread().getName() + "] Load Source resourceName = " + sourceName + ", source = " + source);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "load application source resource error: " + sourceConf, e);
        }
        return;
    }
}
Also used : DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue) Service(org.redkale.service.Service)

Example 3 with Service

use of org.redkale.service.Service in project redkale by redkale.

the class SncpTest method runServer2.

private static void runServer2() throws Exception {
    InetSocketAddress addr = new InetSocketAddress(myhost, port2);
    final CountDownLatch cdl = new CountDownLatch(1);
    final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
    asyncGroup.start();
    new Thread() {

        {
            setName("Thread-Server-02");
        }

        @Override
        public void run() {
            try {
                AnyValue.DefaultAnyValue conf = new AnyValue.DefaultAnyValue();
                conf.addValue("host", "0.0.0.0");
                conf.addValue("port", "" + port2);
                conf.addValue("protocol", protocol);
                SncpServer server = new SncpServer(null, System.currentTimeMillis(), conf, factory);
                Set<InetSocketAddress> set = new LinkedHashSet<>();
                set.add(new InetSocketAddress(myhost, port));
                final TransportFactory transFactory = TransportFactory.create(asyncGroup, protocol.endsWith(".UDP") ? "UDP" : "TCP", 0, 0);
                transFactory.addGroupInfo("server", set);
                Service service = Sncp.createSimpleLocalService(SncpTestServiceImpl.class, null, factory, transFactory, addr, "server");
                server.addSncpServlet(service);
                server.init(conf);
                server.start();
                cdl.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    cdl.await();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Service(org.redkale.service.Service)

Example 4 with Service

use of org.redkale.service.Service in project redkale by redkale.

the class HttpServer method addRestServlet.

/**
 * 添加RestServlet
 *
 * @param <S>             Service
 * @param <T>             HttpServlet
 * @param classLoader     ClassLoader
 * @param name            资源名
 * @param service         Service对象
 * @param userType        用户数据类型
 * @param baseServletType RestServlet基类
 * @param prefix          url前缀
 *
 * @return RestServlet
 */
@SuppressWarnings("unchecked")
public <S extends Service, T extends HttpServlet> T addRestServlet(final ClassLoader classLoader, final String name, final S service, final Class userType, final Class<T> baseServletType, final String prefix) {
    T servlet = null;
    final boolean sncp = Sncp.isSncpDyn(service);
    final String resname = name == null ? (sncp ? Sncp.getResourceName(service) : "") : name;
    final Class<S> serviceType = Sncp.getServiceType(service);
    if (name != null) {
        for (final HttpServlet item : ((HttpPrepareServlet) this.prepare).getServlets()) {
            if (!(item instanceof HttpServlet))
                continue;
            if (item.getClass().getAnnotation(Rest.RestDyn.class) == null)
                continue;
            try {
                Field field = item.getClass().getDeclaredField(Rest.REST_SERVICE_FIELD_NAME);
                if (serviceType.equals(field.getType())) {
                    servlet = (T) item;
                    break;
                }
            } catch (NoSuchFieldException | SecurityException e) {
                logger.log(Level.SEVERE, "serviceType = " + serviceType + ", servletClass = " + item.getClass(), e);
            }
        }
    }
    final boolean first = servlet == null;
    if (servlet == null) {
        servlet = Rest.createRestServlet(classLoader, userType, baseServletType, serviceType);
        if (servlet != null) {
            servlet._reqtopic = MessageAgent.generateHttpReqTopic(Rest.getRestModule(service));
            if (serviceType.getAnnotation(MessageMultiConsumer.class) != null) {
                MessageMultiConsumer mmc = serviceType.getAnnotation(MessageMultiConsumer.class);
                servlet._mmctopic = MessageAgent.generateHttpReqTopic(mmc.module(), resname);
            }
        }
    }
    // 没有HttpMapping方法的HttpServlet调用Rest.createRestServlet就会返回null
    if (servlet == null)
        return null;
    try {
        // 若提供动态变更Service服务功能,则改Rest服务无法做出相应更新
        Field field = servlet.getClass().getDeclaredField(Rest.REST_SERVICE_FIELD_NAME);
        field.setAccessible(true);
        Field mapfield = servlet.getClass().getDeclaredField(Rest.REST_SERVICEMAP_FIELD_NAME);
        mapfield.setAccessible(true);
        Service firstService = (Service) field.get(servlet);
        if (resname.isEmpty()) {
            field.set(servlet, service);
            firstService = service;
        }
        Map map = (Map) mapfield.get(servlet);
        if (map == null && !resname.isEmpty())
            map = new HashMap();
        if (map != null) {
            map.put(resname, service);
            if (firstService != null)
                map.put("", firstService);
        }
        mapfield.set(servlet, map);
    } catch (Exception e) {
        throw new RuntimeException(serviceType + " generate rest servlet error", e);
    }
    if (first)
        this.prepare.addServlet(servlet, prefix, sncp ? Sncp.getConf(service) : null);
    return servlet;
}
Also used : Service(org.redkale.service.Service) Field(java.lang.reflect.Field)

Aggregations

Service (org.redkale.service.Service)4 DefaultAnyValue (org.redkale.util.AnyValue.DefaultAnyValue)2 Field (java.lang.reflect.Field)1 java.net (java.net)1 InetSocketAddress (java.net.InetSocketAddress)1 HttpClient (java.net.http.HttpClient)1 org.redkale.net (org.redkale.net)1 org.redkale.net.http (org.redkale.net.http)1 RedkaleClassLoader (org.redkale.util.RedkaleClassLoader)1