redis启动

cmd-

redis-server.exe (redis.windows.conf)
第二个参数可以写也可以不写

开启

redis-cli.exe -h 127.0.0.1 -p 6379

Java-SpringBoot使用Redis

RedisConfig

其中Bean代表由Spring管理,当Resouorce的name和Bean的name一样时,就会自动通过Bean创建实例.
@Value的字段是在application.properties中,有’.’的话要加${}
这里调用的只是Redis的一个构造函数,传入ip和端口号.

package com.mall.concurrency.cache;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;

@Configuration
public class RedisConfig {

    @Bean(name="redisPool")
    public JedisPool jedispool(@Value("{jedis.host}") String host,@Value("{jedis.port}") int port){
        return new JedisPool(host,port);
    }
}

RedisClient

类似于Orm的操作方式.用完即扔.

package com.mall.concurrency.cache;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

//http://redis.cn/
@Component
public class RedisClient {
    @Resource(name="redisPool")
    private JedisPool jedisPool;

    public void set(String key,String value)throws Exception{
        Jedis jedis=null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    public String get(String key)throws Exception{
        Jedis jedis=null;
        try{
            jedis = jedisPool.getResource();
            return jedis.get(key);
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }
}

CacheController

其中@Autowired和@Resource的区别是:
– @Resource默认按照名称方式进行bean匹配,@Autowired默认按照类型方式进行bean匹配
– @Resource(import javax.annotation.Resource;)是J2EE的注解,@Autowired( import org.springframework.beans.factory.annotation.Autowired;)是Spring的注解

package com.mall.concurrency.cache;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/cache")
public class CacheController {
    @Autowired
    private RedisClient redisClient;

    @RequestMapping("/set")
    @ResponseBody
    public String set(@RequestParam("k") String k,@RequestParam("v") String v)throws Exception{
        redisClient.set(k, v);
        return "SUCCESS";
    }

    @RequestMapping("/get")
    @ResponseBody
    public String get(@RequestParam("k") String k)throws Exception{
        return redisClient.get(k);
    }

}

application.properties的书写格式

# redis
jedis.host=127.0.0.1
jedis.port=6379