Springboot uses Jedis code to dynamically configure Redis

Springboot uses Jedis code to dynamically configure Redis

Project requirements, Party A's requirements are for security purposes and do not want some configuration information in properties to be reflected in the file, and may need to modify the corresponding configuration through the page later, so the solution is to store part of the configuration information in the database. Then use @Bean injection to inject it into springboot, and then configure it directly with code, for example: Redis.

environment

  • Java 1.8
  • Springboot 2.0
  • MySQL 5.7
  • Redis 3.0

pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

Create an object to save Redis related configuration information, here simply set the url and port

public class RedisConfig {
    private String url;
    private int port;
    //省略get set
}

Obtain the corresponding configuration information from the database. Because the design of the database is a bit problematic, the structure is id, keyName, value, so temporarily obtain a configuration url

@Mapper
public interface ConfiguresMapper {
    @Select("SELECT * FROM configures WHERE keyName = #{key}")
    Configures getOneByKey(@Param("key") String key);
}

Then it is to inject @Bean in the entry file, so that @Autowired can be used globally for automatic injection and introduction

@SpringBootApplication
public class DemoApplication {
    @Autowired
    private ConfiguresMapper configuresMapper;

    @Bean
    public RedisConfig configures() {
        //从数据库获取url,也就是host
        Configures configures = configuresMapper.getOneByKey("redisURL");
        RedisConfig redisConfig = new RedisConfig();
        //直接设置port,实际是从数据库获取,等待数据表结构重新设计后,进行更改
        redisConfig.setPort(6379);
        redisConfig.setUrl(configures.getValue());
        return redisConfig;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

At this point, the injection process is complete, and the next step is to introduce and use it.

Manipulating Redis with Jedis

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableAutoConfiguration
public class RedisConfig {
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    //因为命名出现了重复,所以需要注入引入的路径
    @Autowired
    private com.example.demo.Entity.RedisConfig redisConfig;
    @Bean
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    public JedisPool getJedisPool() {
        JedisPoolConfig config = getRedisConfig();
        logger.info("---------"+redisConfig.getUrl());
        logger.info("---------"+redisConfig.getPort());
        JedisPool jp = new JedisPool(config, redisConfig.getUrl(), redisConfig.getPort());
        return jp;
    }
}

Jedis operation

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

@Service
public class RedisService {
    private static final Logger logger = LoggerFactory.getLogger(RedisService.class);
    @Autowired
    private JedisPool jedisPool;

    public String get(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            logger.info("Redis get success - " + key + ", value:" + str);
            result = str;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return result;
    }
}

A problem here is that jedis is not released, so you need to add a release operation

Write a Controller for testing

@RestController
@RequestMapping("/test")
public class TestController{
    @Autowired
    private RedisConfig redisConfig;
    @Autowired
    private RedisService redisService;

    @RequestMapping(value = {"/", ""})
    public String hellTask() {
        Configures configures = new Configures();
        int port = redisConfig.getPort();
        String url = redisConfig.getUrl();
        String value = redisService.get("ket");
        return "Port: " + port + "-----" + url + "---value---" + value;
    }
}

Then visit localhost:8080/test/
write picture description here

So far the overall requirements are met, and the rest is to apply it to the actual project for testing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324505230&siteId=291194637