NutzCN Logo
问答 redis 空指针异常
发布于 2408天前 作者 文涛(wentao) 3212 次浏览 复制 上一个帖子 下一个帖子
标签:

调用redis空指针异常
redis.properties 文件放在项目的 resources/custom目录下

redis.host=localhost
redis.port=6379
redis.timeout=2000
redis.database=0

redis类:

@IocBean(name="redis")
@IocBy(args={
        "*js", "ioc/",
        "*anno", "demo.hello",
        "*jedis" // 是的,并没有什么参数
})
public class cust_redis {
    @Aop("redis")
    public Long getSize() {
        return jedis().dbSize();
    }
}

调用方法:

public static void main(String[] args) {
        System.out.println(new cust_redis().getSize());
}
10 回复

ioc里面的对象才能用, 直接new出来的对象是不行的

从ioc容器取出来才可以的

我在外面只是去返回值,没有直接调用内部对象啊

没有"内部对象", cust_redis必须从ioc容器取, @Aop才有意义

那我现在要怎么做才能正确获取到redis对象呢

ioc.get(cust_redis.class);

我是不是还需要先

ioc = new NutIoc(new JsonLoader("ioc/redis.js"));

然后

ioc.get(cust_rediss.class)

你应该做个全局的ioc容器

看了redis.js的实例文件,我这样做可以了
redis.js

var ioc = {
    // 参考 https://github.com/xetorthio/jedis/wiki/Getting-started
    conf : {
        type : "org.nutz.ioc.impl.PropertiesProxy",
        fields : {
            paths : ["custom/"]
        }
    },
    jedisPoolConfig : {
        type : "redis.clients.jedis.JedisPoolConfig",
        fields : {
            testWhileIdle : true, // 空闲时测试,免得redis连接空闲时间长了断线
            maxTotal : {java : "$conf.getInt('redis.maxTotal', 100)"} // 一般都够了吧
        }
    },
    jedisPool : {
        type : "redis.clients.jedis.JedisPool",
        args : [
            {refer : "jedisPoolConfig"},
            // 从配置文件中读取redis服务器信息
            {java : "$conf.get('redis.host', 'localhost')"},
            {java : "$conf.getInt('redis.port', 6379)"},
            {java : "$conf.getInt('redis.timeout', 2000)"},
            {java : "$conf.get('redis.password')"},
            {java : "$conf.getInt('redis.database', 0)"}
        ],
        fields : {},
        events : {
            depose : "destroy" // 关闭应用时必须关掉呢
        }
    },
    redis : {
        type : "org.nutz.integration.jedis.RedisInterceptor",
        fields : {
            jedisPool : {refer:"jedisPool"}
        }
    },
    redisService : {
        type : "org.nutz.integration.jedis.RedisService"
    },
    pubSubService : {
        type : "org.nutz.integration.jedis.pubsub.PubSubService",
        fields : {
            jedisPool : {refer:"jedisPool"}
        },
        events : {
            depose : "depose"
        }
    }
};

public static Ioc ioc;

private static final Log log = Logs.getLog(bind_ppv_asset.class);

static {
    ioc = new NutIoc(new JsonLoader("ioc/jedis.js"));
}


public static void main(String[] args) {

    RedisService redisService = ioc.get(RedisService.class, "redisService");

    System.out.println(redisService.dbSize());

}

```

除了conf,其他都在jedis插件里面有, 加*jedis 就可以了

添加回复
请先登陆
回到顶部