springboot 整合Redis-Jedis

允我心安 提交于 2020-10-29 01:02:00

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xiao</groupId>
    <artifactId>boot-jedis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-jedis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.1.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

server:
  port: 8080
spring:
  redis:
    host: 192.168.1.11
    password: 123456
    port: 6379
    jedis:
      pool:
        max-idle: 8 #最大空闲数
        max-active: 10 #最大连接数
        min-idle: 0 #最小空闲数
    timeout: 20000 #连接超时时间

jedisconfig

package com.xiao.bootjedis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * jedis连接池
 */
@Configuration//定义配置类
public class JedisConfig {

   private Logger logger=LoggerFactory.getLogger(JedisConfig.class);

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Bean
    public JedisPool JedisPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();//连接池配置

        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxTotal(maxActive);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port,timeout,password);//连接池

        logger.info("JedisPool连接成功:"+host+"\t"+port) ;
        return  jedisPool;
    }


}

user

package com.xiao.bootjedis.bean;


public class User {

    private Long id;

    private String name;

    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

demoservice

package com.xiao.bootjedis.service;

import com.xiao.bootjedis.bean.User;

public interface DemoService {

    //(String)获取key对应的值,如果redis有则在redis进行查询返回,没有则查询数据库
    String getString(String user);

    //(Hash)获取key对应的值,如果redis有则在redis进行查询返回,没有则查询数据库并存入redis
    User getHash(String user);


}

demoserviceimpl

package com.xiao.bootjedis.service.impl;

import com.xiao.bootjedis.bean.User;
import com.xiao.bootjedis.service.DemoService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@Log
@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private JedisPool jedisPool;


    /**
     * 获取key对应的值,如果redis有则在redis进行查询返回,没有则查询数据库
     * @return
     */
    @Override
    public String getString(String name) {

        Jedis jedis = jedisPool.getResource();//获取连接
        if(jedis.exists(name)){
            log.info("redis查询");
            jedis.close();//关闭连接
            return jedis.get(name);

        }else{
            jedis.close();//关闭连接
            log.info("mysql查询");
            return "123455";
        }

    }

    /**
     * (Hash)获取key对应的值,如果redis有则在redis进行查询返回,没有则查询数据库并存入redis
     * @param name
     * @return
     */
    @Override
    public User getHash(String name) {
        Jedis jedis = jedisPool.getResource();//获取连接
        if(jedis.exists(name)){//存在
            log.info("redis查询");


            Map<String, String> map = jedis.hgetAll(name);


            User user = new User();
            user.setId(Long.valueOf(map.get("id")));
            user.setName(map.get("name"));
            user.setAge(Integer.valueOf(map.get("age")));
            jedis.close();//关闭连接
            return user;//获取

        }else{//不存在
            log.info("mysql查询");
            User user = new User();
            user.setId(1L);
            user.setName("zhangsan");
            user.setAge(16);
            Map<String, String> map = new HashMap<>();
            map.put("id",user.getId().toString());
            map.put("name",user.getName());
            map.put("age",user.getAge().toString());

            jedis.hset(name, map);//存入redis
            jedis.close();//关闭连接
            return user;
        }

    }



}

测试类

package com.xiao.bootjedis;

import com.xiao.bootjedis.bean.User;
import com.xiao.bootjedis.service.DemoService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.JedisPool;

@SpringBootTest
class BootJedisApplicationTests {

    @Autowired
    private DemoService demoService;


    @Test
    void testGetString(){
        String user = demoService.getString("key1");
        System.out.println(user);
    }

    @Test
    void testGetHash(){
        User user = demoService.getHash("user");
        System.out.println(user.toString()+"---> id:"+user.getId()+" name:"+user.getName()+" age:"+user.getAge());
    }

    @Test
    void contextLoads() {

    }

}

链接:https://pan.baidu.com/s/1umBMvkL17SNnYBsHSKlf9Q 
提取码:gsj8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!