Set up eureka,gateway,admin,redis,docker series. Redis and redisapi are together

Posted by l00ph0le on Thu, 26 Mar 2020 16:09:58 +0100

This chapter covers the redis interface Aspect signature swagger2

1. Install redis on Linux centOS server. Go to the Internet for specific installation commands. It's relatively simple. I used the config set maxmemory policy volatile LRU policy

2. Create an empty module project

Add pom dependency

<dependencies>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency> 
        <!--Registry dependency-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.dixintong</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Register yourself with the registry and be discovered by admin

Create a startup class

@SpringBootApplication
@RestController
public class RedisapiApplication extends SpringBootServletInitializer {
    public static void main(String[] args) throws IOException { 
        SpringApplication.run(RedisapiApplication.class, args);

    }


}

Profile

server:
  port: 9101
spring:
  application:
    name: redisapi
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka
  instance:
    status-page-url-path: /actuator/info
    metadata-map.management:
      context-path: /actuator
    health-check-url-path: /actuator/health
management:
  endpoints:
    web:
      exposure:
        include: '*'
    health:
      show-details: ALWAYS
info:
  version: 1.0.0

Register with the registry, check URL path is found by admin

After creating a Swagger2Config class, you will use the

@EnableSwagger2
@Configuration
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                //.host("Local access comments, online access to write domain name address")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxxx.redisapi.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-api File")
                .description("swagger Access tutorial")
                //Terms of service website
                .termsOfServiceUrl("http://www.xxxx.com/privacy.aspx")
                .version("1.0")
                .contact(new Contact("xxx", "http://www.xxx.com", "xx@xxx.com"))
                .build();
    }

}

Create SignAspect

@Aspect
@Component
public class SignAspect {
    @Around("@annotation(Your project directory.aspect Folder.Sign)")
    public Object doAccessCheck(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("---start sign");
        Sign aspect = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(Sign.class);
        boolean verify = false;
        if (pjp.getArgs().length > 0 && aspect.type() == SignType.SIGN_MD5) {
            Object params = pjp.getArgs()[0];
            JSONObject jsonParam = JSON.parseObject(params.toString());
            String timeStamp = jsonParam.getString("timeStamp");
            String[] value = aspect.value().split(",");
            String tmpValue = "";
            JSONObject data = jsonParam.getJSONObject("data");
            for (String val : value) {
                tmpValue += val + data.getString(val);
            }
            String md5keyapp = CommonKey.REDISKEY;
            String sign = jsonParam.getString("sign").toLowerCase();
            String pjSign = MD5.getMD5(md5keyapp + timeStamp + tmpValue, 32).toLowerCase();
            verify = pjSign.equals(sign);
        }
        if (verify) {
            Object object = pjp.proceed();
            return object;
        } else {
            ResponseModel model = new ResponseModel();
            model.setAPIState(APIState.KeysFail);
            return model;
        }
    }
}

My interface is post. The request parameters are json / / {"data":{"op":"get","key":"username"},"sign":"md5 encryption", "timeStamp":1581992205704}

I use this type of encryption

Create Sign

@Target(METHOD)
@Retention(RUNTIME)
@Documented
public @interface Sign {
    
    String desc() default "Start signature verification...";

   
    SignType type() default SignType.SIGN_MD5;

    
    String value() default "";
}

Create SignType

public enum SignType {
    /**
     * MD5 encryption
     */
    SIGN_MD5;
}

Create a class

@RestController
@RequestMapping("/redis")
@Api(tags = "redisapi File", hidden = true)
public class managerHelper {
 
//Encryption can be seen here
    @ApiOperation(value = "redis Operation interface POST request JSON parameter op There are currently five operations set,get,del,append,lset", notes = "Default parameters {\"data\":{\"op\":\"get\",\"key\":\"test5\"},\"sign\":\"md5 encryption\",\"timeStamp\":1581992205704}")
    @RequestMapping(value = "/opRedis", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @Sign(value = "op,key")
    public @ResponseBody
    ResponseModel getRedis(@RequestBody JSONObject jsonParam) {
        ResponseModel model = new ResponseModel();
        Jedis jedis = RedisUtil.getJedis();
        try {
            //set operation reserved
            String op = jsonParam.getJSONObject("data").getString("op");
            String key = jsonParam.getJSONObject("data").getString("key");

            if (op.equals("set")) {
                String value = jsonParam.getJSONObject("data").getJSONObject("value").toJSONString();

                if (value != "" && value != null) {
                    Integer expdatesec = jsonParam.getJSONObject("data").getInteger("expdatesec");

                    int secLong = 0;
                    if(expdatesec==null){
                        expdatesec=0;
                    }
                    if (expdatesec > 0) {
                        secLong = expdatesec;
                    } else {
                        int max = 14400, min = 7200;//2 hours minimum and 4 hours maximum
                        secLong = (int) (Math.random() * (max - min) + min);
                    }

                    jedis.setex(key, secLong, value);
                    model.setAPIState(APIState.Success);
                } else {
                    model.setAPIState(APIState.NoMoreData);
                }
            } 

        } catch (Exception ex) {
            model.setAPIState(APIState.Fail);
        } finally {
            RedisUtil.returnResource(jedis);
        }


        return model;
    }


}

 

Create a Redis class

public class RedisUtil {

    //The server IP address
    private static String ADDR = "redisIP address";
    //port
    private static int PORT = 6379;
    //Password
    private static String AUTH = "redis Access password";
    //Maximum number of connections for connection instances
    private static int MAX_ACTIVE = 1024;
    //Control one pool How many states are there at most idle(Idle)Of jedis Instance, the default value is also 8.
    private static int MAX_IDLE = 200;
    //The maximum time, in milliseconds, to wait for an available connection. The default value is-1,Means never time out. If the waiting time is exceeded, it will be thrown directly JedisConnectionException
    private static int MAX_WAIT = 10000;
    //Connection timeout time  
    private static int TIMEOUT = 10000;
    // stay borrow One jedis Whether to advance the instance validate Operation; if true,Obtained jedis All instances are available;
    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;
    //Database mode is 16 databases 0~15
    public static final int DEFAULT_DATABASE = 0;
    /**
     * Initialize Redis connection pool
     */

    static {

        try {

            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT,AUTH,DEFAULT_DATABASE);

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    /**
     * Get Jedis instance
     */

    public synchronized static Jedis getJedis() {

        try {

            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                System.out.println("redis--Service is running: "+resource.ping());
                return resource;
            } else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /***
     *
     * Release resources
     */

    public static void returnResource(final Jedis jedis) {
        if(jedis != null) {
            jedis.close();
        }
    }
}

Call step start eureka start gateway start admin start redisapi use postman request

Topics: Java Jedis Redis Spring JSON