Springboot +Redis简单搭建_06

1.首先下载安装好本机的Redis

Redis官网下载安装 : http://www.runoob.com/redis/redis-install.html

2.引入jedis jar包

	<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.8.2</version>
	</dependency>

3.在Application配置文件中加入redis属性

#设置本地host
#设置端口号
#设置最大连接数
#maxIdle:控制一个pool最多有多少个状态为idle的jedis实例,设置空间连接设置空间连接
#设置最大阻塞时间,记住是毫秒数milliseconds

jedis.host = 127.0.0.1
jedis.port = 6379
jedis.maxTotal = 101
jedis.maxIdle = 10
jedis.maxWaitMillis = 100000

4.添加Jedis实体类

@Data
//@ConfigurationProperties的大致作用就是通过它可以把properties或者yml配置直接转成对象
@ConfigurationProperties(prefix = JedisProperties.JEDIS_PREFIX)
//对 redis 配置参数进行读取和绑定,配置属性注入到 JedisProperties
public class JedisProperties {

    //这里也可以不选择配置一个常量,@ConfigurationProperties(prefix = jedis) 即可
    public static final String JEDIS_PREFIX = "jedis";

    private String host;

    private int port;

    private int maxTotal;

    private int maxIdle;

    private int maxWaitMillis;

}

5.添加Jedis配置类

//配置了 Redis 连接池之后,将 Redis 连接池 注入到 RedisClient 中,并生成 RedisClient Bean
@Configuration
@EnableConfigurationProperties(JedisProperties.class)//开启属性注入,通过@autowired注入
@ConditionalOnClass(RedisClient.class)//判断这个类是否在classpath中存在
public class JedisAutoConfiguration {

    @Autowired
    private JedisProperties prop;

    @Bean(name="jedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(prop.getMaxTotal());
        config.setMaxIdle(prop.getMaxIdle());
        config.setMaxWaitMillis(prop.getMaxWaitMillis());
        return new JedisPool(config, prop.getHost(), prop.getPort());
    }

    @Bean
    @ConditionalOnMissingBean(RedisClient.class)//容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
    //这个注解可以使用在字段和参数上,默认使用为空(这个注解要和@AutoWired一起使用,否则无法注入)
    //@Autowired默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,则需要限定其中一个候选者,否则将抛出异常
    //@Qualifier限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者
    public RedisClient redisClient(@Qualifier("jedisPool")JedisPool pool) {
        RedisClient redisClient = new RedisClient();
        redisClient.setJedisPool(pool);
        return redisClient;
    }
}

6.Redis常用操作

@Data
//常用的 redis 的操作
public class RedisClient {

    private JedisPool jedisPool;

    /**
     * 将数据加载到redis中的方法 一般是用set. 如下列方法,这里指定value是String类型,也是因为我的业务关系把value转成了json串~
     * @param key
     * @param value
     * @throws Exception
     */
    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();
            }
        }
    }
}

7.freemarker代码

<div>
        <span>输入key<input type="text" name="key" ></span><p>
        <span>输入value<input type="text" name="value" ></span><p>
        <input type="button" value="提交" id="setter" onclick="setter();"><p>
        <input type="button" value="拿取" id="getter" onclick="getter();"><p> 
</div>

<script>

    function setter(){
        var key = $('input[name="key"]').val();
        var value = $('input[name="value"]').val();
        /*$.get('/set',{"key":key,"value":value},function(result1){
            if(result1!=null){
                alert(result1)
            }
        });
        */
        //使用这种方式提交,后台传字符串可能会进error,改为boolean可以使用
         $.ajax({
             url:'set',
             type:'post',
             data:{"key":key,"value":value},
             dataType:'json',
             success:function (data) {
                 if(data==true){
                     alert(data);
                 }
             },
             error:function(){
                 alert("正在尝试重新连接...");
             }
         });
    }

    function getter(){
        var key = $('input[name="key"]').val();
        $.get("/get",{"key":key},function(result1){
            if(result1!=null){
                $('input[name="value"]').val(result1);
            }
        });
       /* $.ajax({
            url:'get',
            type:'post',
            data:{"key":key},
            dataType:'json',
            success:function (data) {
                if(data!=null){
                    alert(data);
                }
            },
            error:function(){
                alert("正在尝试重新连接...");
            }
        });*/
    }
</script>

8.controller页面

@Controller
public class TestController {

    @Autowired
    private RedisClient redisClient;

    @RequestMapping("set")
    @ResponseBody
    public Boolean set(String key,String value) throws Exception{
        redisClient.set(key, value);
        return true;
    }

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

9.效果如下:

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44100514/article/details/86600140
今日推荐